1

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?

2 Answers 2

3
 for(int ndx = rGen.nextInt() + 1; ndx <= 9;){

This looks fishy. Random.nextInt() returns a random integer within the integer's full range, not just from 0 to 9.

Sign up to request clarification or add additional context in comments.

2 Comments

Okay, so I fixed that, but it's just returning zeros. I saw on a board that I am supposed to use random indexes instead of random input values. If it's not too much to ask for, could you show me how to implement that? Thanks a bunch.
I don't understand what you are asking, you need to be more specific.
0

You'll want this.

public int nextInt(int n) Returns: a pseudorandom, uniformly distributed int value between 0 (inclusive) and n (exclusive).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.