在c ++中随机播放一个3d数组

时间:2013-03-23 16:17:48

标签: c++ magic-square

我有这段代码创建一个3d数组并将1-9放在3x3x3框中。我需要找到一种方法来重新排列这个数组的元素,以比较新洗牌的数组与魔方的接近程度。任何想法都表示赞赏!谢谢!

 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;
}

2 个答案:

答案 0 :(得分:0)

您可以使用std::random_shuffle(...),但必须正确使用它才能拥有真正的随机排列。 迭代地在2D数组上使用random_shuffle将在每行的相关条目中产生。

#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;
}

在线演示:http://ideone.com/C4PlRs

答案 1 :(得分:-1)

您可以使用std::random_shuffle来重新排列数组。