Search code examples
c++magic-square

shuffle a 3d array in c++


I have this piece of code which creates a 3d array and places 1-9 in a 3x3x3 box. I need to find a way to shuffle the elements of this array to compare how closely the newly shuffled array is to a magic square. Any ideas are appreciated! Thanks!

 for(i = 0; i < x; i++)
{
    cout << "Finding a Magic Square..." << endl;

    for(j = 0; j < y; j++)
    {
        cout << endl;

        for(k = 0; k < z; k++)
        {
            array3D[i][j][k] = (i+1) + (j * z) + k;
            cout << '\t' << array3D[i][j][k];
        }
    }

    cout << endl << endl;
}

Solution

  • You can use std::random_shuffle(...) but you have to use it properly to have truly random permutations. Iteratively using random_shuffle on a 2D array will yield in related entries per row.

    #include <algorithm>
    #include <iterator>
    #include <iostream>
    #include <cstdlib>
    #include <ctime>
    
    int main () {
        std::srand(std::time(NULL)); // initialize random seed
    
        // shuffle a 2D array
        int arr[3][3] = {
            {0, 1, 2},
            {3, 4, 5},
            {6, 7, 8}
        };
    
        // Shuffle from the first member to the last member.
        // The array is interpreted as a 9 element 1D array.
        std::random_shuffle(&arr[0][0], &arr[2][3]);
    
        // print the result
        for (int row = 0; row < 3; ++row) {
            for (int col = 0; col < 3; ++col) {
                std::cout << arr[row][col] << ' ';
            }
            std::cout << std::endl;
        }
        return 0;
    }
    

    Online demo: http://ideone.com/C4PlRs