I'm having an issue with creating a random Sudoku grid. I tried modifying a recursive pattern that I used to solve the puzzle. The puzzle itself is a two dimensional integer array. This is what I have (By the way, the method doesn't only randomize the first row. I had an idea to randomize the first row, then just decided to do the whole grid):
public boolean randomizeFirstRow(int row, int col){
Random rGen = new Random();
if(row == 9){
return true;
}
else{
boolean res;
for(int ndx = rGen.nextInt() + 1; ndx <= 9;){
//Input values into the boxes
sGrid[row][col] = ndx;
//Then test to see if the value is valid
if(this.isRowValid(row, sGrid) && this.isColumnValid(col, sGrid) && this.isQuadrantValid(row, col, sGrid)){
// grid valid, move to the next cell
if(col + 1 < 9){
res = randomizeFirstRow(row, col+1);
}
else{
res = randomizeFirstRow( row+1, 0);
}
//If the value inputed is valid, restart loop
if(res == true){
return true;
}
}
}
}
//If no value can be put in, set value to 0 to prevent program counting to 9
setGridValue(row, col, 0);
//Return to previous method in stack
return false;
}
This results in an ArrayIndexOutOfBoundsException with a ridiculously high or low number (+- 100,000). I've tried to see how far it goes into the method, and it never goes beyond this line:
if(this.isRowValid(row, sGrid) && this.isColumnValid(col, sGrid) && this.isQuadrantValid(row, col, sGrid))
I don't understand how the array index goes so high. Can anyone help me out?