Generating a Sudoku Board in C

1.3k Views Asked by At

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?

2

There are 2 best solutions below

0
On

Since this is a homework I will give you a little hint, not the solution.

display[i] = grid[rand() % 9 + 1];

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.

display[i] = grid[i];

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 generated 0 1 4 5, you take 0 1 10 11. Then you proceed to copy display[i] = grid[i] where i is 0 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.

0
On

Firstly I'd recommend having two-dimensional arrays(considering that a sudoku board is two-dimensional), and use a nested loop to fill those boards. Also, you would need to use the ranges (0-2), (3-5), and (6-8) as guides to which blocks make up which regions. Here, each block is a 3x3 region, and in each region is the set of indices for the x and y (assuming that the origin is the upper left hand corner). This image shows which regions are which

Just randomly choose numbers in these regions. The algorithm shouldn't be too tricky

ADDENDUM: display[] is not a function; it's an array