Search code examples
javagrid-layoutsudoku

Java - Select a number from every square in a 9x9 grid


I have a 9x9 sudoku grid and I need to get a random number from every 3x3 square in the grid.

The most awful code would be something like this:

    if(square == 0) {
        row = random.nextInt(3);
        col = random.nextInt(3);
    }

    if(square == 1) {
        row = random.nextInt(3);
        col = random.nextInt(3) + 3;
    }
    if(square == 2) {
        row = random.nextInt(3);
        col = random.nextInt(3) + 6;
    }
    if(square == 3) {
        row = random.nextInt(3) + 3;
        col = random.nextInt(3);
    }
    if(square == 4) {
        row = random.nextInt(3) + 3;
        col = random.nextInt(3) + 3;
    }
    if(square == 5) {
        row = random.nextInt(3) + 3;
        col = random.nextInt(3) + 6;
    }
    if(square == 6) {
        row = random.nextInt(3) + 6;
        col = random.nextInt(3);
    }
    if(square == 7) {
        row = random.nextInt(3) + 6;
        col = random.nextInt(3) + 3;
    }
    if(square == 8) {
        row = random.nextInt(3) + 6;
        col = random.nextInt(3) + 6;
    }

where square is the index of the square in the grid (square = 0,1,...,8)

I cannot figure out how to write it in a better way.

Some ideas? Thanks


Solution

  • This should work for any square size. In your case is 3x3, so size is 3.

    int size = 3;
    row = random.nextInt(size) + (square / size) * size;
    col = random.nextInt(size) + (square % size) * size;