Hi guys I have an assignment for my C class and I needed some help with one of the functions.
For Example,
void genSudokuBoard(int grid[ ], int display[ ])
This function uses the 81 element 'grid' array (containing a fully completed list of valid Sudoku values) and randomly copies 4 numbers from each 3x3 block into the corresponding positions in the 81 element 'display' array. The random numbers chosen will be by array position (index), so for example, given that the top left 3x3 block consists of the array indexes: entire 3x3 block: 0, 1, 2, 9, 10, 11, 18, 19, 20 4 random indexes might be: 2, 10, 11, 19
And so far, I have this,
void genSudokuBoard(int grid[], int display[])
{
int i;
for (i = 0; i < 81; i++){
display[i] = grid[rand() % 9 + 1];
}
}
Basically my question is, how can i copy 4 random numbers from each 3x3 block into the corresponding position in the display[] array?
Since this is a homework I will give you a little hint, not the solution.
here you copy from a random grid index to
display[i]
. This is definitely not what you want. When you copy you need to copy to the same index. I.e.You just have to choose which
i
to copy and witch not.You need to generate 4 random numbers from 9 numbers. For instance in your example you have to determine the 9 indexes that make a grid:
0, 1, 2, 9, 10, 11, 18, 19, 20
. That is a set of 9 values so you could generate 4 distinct indexes 0<=r<9. You take from this set only from the 4 generated indexes. So if you generated0 1 4 5
, you take0 1 10 11
. Then you proceed to copydisplay[i] = grid[i]
wherei
is0 1 10 11
.Of course there are other approaches to this.
My advice is to approach this problem bottom-up. That is once you identify the algorithm (like the one I gave you) you should try to tackle the small problems. For instance you should first figure out how to generate the 9 indexes that make a grid. Independent of that you should figure out how to generate k distinct numbers in an interval. You do all this in contained units, completely ignoring the rest of the problem. Then you can go about merging those into your final problem.