如何在行和列之间生成具有不同数字的二维数组?

问题描述 投票:0回答:1
    void generateSudoku(int sudoku[][C])
            {
                for (int i = 0; i < R; i++)
                {
                    for (int j = 0; j < C; j++)
                    {
                        sudoku[i][j] = generateRandNum(); //generate random number for all 2d array
                        while (sudoku[1][0] == sudoku[0][0] || sudoku[2][0] == sudoku[1][0] || sudoku[2][0] == sudoku[0][0]
                            || sudoku[3][0] == sudoku[2][0] || sudoku[3][0] == sudoku[1][0] || sudoku[3][0] == sudoku[0][0])
                            sudoku[i][j] = generateRandNum();
                        while (   sudoku[i][1] == sudoku[i][0] || sudoku[1][1] == sudoku[0][1] || sudoku[2][1] == sudoku[1][1]
                               || sudoku[2][1] == sudoku[0][1] || sudoku[3][1] == sudoku[2][1] || sudoku[3][1] == sudoku[1][1]
                               || sudoku[3][1] == sudoku[0][1]) //index 1 to index 0
                            sudoku[i][j] = generateRandNum();
                        while ( (sudoku[i][2] == sudoku[i][0]) || (sudoku[i][2] == sudoku[i][1]) || sudoku[1][2] == sudoku[0][2]
                               || sudoku[2][2] == sudoku[1][2] || sudoku[2][2] == sudoku[0][2] || sudoku[3][2] == sudoku[2][2]
                               || sudoku[3][2] == sudoku[1][2] || sudoku[3][2] == sudoku[0][2])
                            sudoku[i][j] = generateRandNum();
                        while ( (sudoku[i][3] == sudoku[i][0]) || (sudoku[i][3] == sudoku[i][1]) || (sudoku[i][3] == sudoku[i][2])) //index 3 to index 2,1,0
                            sudoku[i][j] = generateRandNum();
                    }

                }
            }

是否有更有效和简单的方法来生成具有随机数的二维数组,这些数据与每个列和行一样独特?代码有效,但执行时间太长,可能是由很多循环引起的。我也是初学者(第一年cs学生),所以这是我能想到的唯一方法让它与众不同(是的,我知道它的愚蠢,低效和错误),因为我不知道如何做复杂的算法。

编辑:generateRandNum:

int generateRandNum()
{
    int randNum;
    randNum = (rand() % 4)+1;
    return randNum;
}
c++ arrays random distinct sudoku
1个回答
0
投票

我不知道这是否有用,但我在另一个thread中找到了一个简单的算法来生成一个完整的数独谜题。有关更多详细信息,请查看此主题。这是我对此算法的简短实现:

std::array <unsigned int, 9> seed = {8, 9, 3, 2, 7, 6, 4, 5, 1};

std::array <std::array <unsigned int, 9>, 9> generate(std::array
    <unsigned int, 9> seed)
{
    unsigned int seedOffset {0};
    std::array <std::array <unsigned int, 9>, 9> field;

    field.at(0) = seed;

    for(unsigned int fieldIndex {1}; fieldIndex < field.size(); ++fieldIndex)
    {
        seedOffset = (0 == (fieldIndex % 3)) ? 1 : 3;
        std::rotate(seed.begin(), seed.begin() + seedOffset, seed.end());
        field.at(fieldIndex) = seed;
    }

    return field;
}
© www.soinside.com 2019 - 2024. All rights reserved.