dimanche 17 décembre 2017

How do I generate 2d array with distinct number between row and column?

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

                }
            }

Is there more efficient and easy way to generate 2d array with random numbers that is distinct with each column and row like a sudoku? The code works, but execution time is too long, probably caused by so many loops. Also I'm a beginner (first year cs students) so this is the only way I can think of to make it distinct (yeah i know its stupid and inefficient and wrong), as I don't know how to do complex algorithm.




Aucun commentaire:

Enregistrer un commentaire