简体   繁体   中英

recursive validation function stack overflow

I'm creating a console application that creates a random sudoku table.

I'm having trouble with the validation of the table (except the 3x3 box validation which still needs work) and that works perfectly but after so many loops of the x and y of the 9x9 sudoku table I get given a stack overflow error. I am not sure how to stop this from happening.

This is the code:

int Array[9][9];
int validate(int i, int j, int *number){
  *number = rand() % 9 + 1;
  for (int x = 0; x < 9; x++){ //row validation 
      if (*number == Array[x][j]){
            validate(i,j,number);
      }
  }

  for (int x = 0; x < 9; x++){ //column validation
      if (*number == Array[i][x]){
            validate(i,j,number);
      }
  }

  return *number;
}

void generate(){
  for (int x = 0; x < 9; x++){
     for (int y = 0; y < 9; y++){
         int *number = new int;
         Array[x][y] = validate(x,y,number);
         delete number;
     }
   }
 }


int main(){
  srand((unsigned int)time(NULL));
  generate();
}

I think I to use dynamic memory allocation such as malloc or new ? But I'm not sure how to use them within the validate() function which is where I am getting the stack overflow error.

First, your code has several basic C++ issues :

  • You are using pointers to int with dynamic allocation where simple stack allocated int are enough
  • You are using rand() from th C library, coupled with a modulo, resulting in a very poor distribution , consider the standard <random> header instead.
  • You use needless global variables ( Array ), you should avoid that.

Now, your real problem is mathematical .

You are trying to randomly generate a sudoku table : this is not possible in a deterministic fashion.

Explanation:

For (i, j) in [1-9] x [1-9] :

  • Consider the cell (i , j) : for this cell, you already have i - 1 random numbers on the line and j - 1 numbers on the column, So (i + j - 2) numbers.

  • Now if we take i + j = 11 (eg i = 4, j = 7 ), we have 9 random numbers already generated on either the line or the column. We come to cases where all numbers in [1 - 9] already exist either in the line or in the column (nothing in your code prevented it), making impossible to generate a number for the current cell, hence infinite recursion (the validate method can never succeed), hence Stack Overflow .

There are plenty of deterministic algorithms on the web to generate Sudoku tables, you should start by looking at it.

Note:

If you are terribly lucky, your program could generate a valid Sudoku table. If it does, consider playing the national lottery.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM