How would I shuffle a 2D array?

closed account (4iwkoG1T)
I have a 2D array with 108 strings. How do I shuffle it correctly?
I don't think I'm doing it right
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <string>
#include <algorithm>
#include <iterator>

int main()
{
    // the hard, inefficient way
    {
        enum { N = 7, M = 13 } ;
        char dest[N][M] = { "zero", "one", "two", "three", "four", "five", "six" } ;

        std::srand( std::time(nullptr) ) ;

        for( int i = N-1 ; i > 0 ; --i ) // fisher yates shuffle
        {
            const int pos = std::rand() % (i+1) ;
            char temp[M] ;
            std::strcpy( temp, dest[pos] ) ;
            std::strcpy( dest[pos], dest[i] ) ;
            std::strcpy( dest[i], temp ) ;
        }

        for( const char* cstr : dest ) std::cout << cstr << ' ' ;
        std::cout << '\n' ;
    }

    // the simple, efficient way
    {
        enum { N = 7 } ;
        std::string dest[N] = { "zero", "one", "two", "three", "four", "five", "six" } ;

        std::srand( std::time(nullptr) ) ; // if it has not already been done

        std::random_shuffle( std::begin(dest), std::end(dest) ) ;

        for( const std::string& str : dest ) std::cout << str << ' ' ;
        std::cout << '\n' ;
    }
}

http://ideone.com/3MTUkq
Topic archived. No new replies allowed.