2

I am writing a sudoku board game generator. My code looks like this:

/**
 * Created by szubansky on 3/9/16.
 */

public class SudokuBoard {

    static int N = 9;
    static int[][] grid = new int[N][N];

    static void printGrid()
    {
        for (int row = 0; row < N; row++)
        {
            for (int col = 0; col < N; col++) {
                System.out.printf("%5d", grid[row][col]);
            }
            System.out.println("\n");
        }
    }

    private static boolean checkRow(int row, int num)
    {
        for( int col = 0; col < 9; col++ )
            if(grid[row][col] == num)
                return false;

        return true;
    }

    private static boolean checkCol(int col, int num)
    {
        for( int row = 0; row < 9; row++ )
            if(grid[row][col] == num)
                return false;

        return true;
    }

    private static boolean checkBox(int row, int col, int num)
    {
        row = (row / 3) * 3;
        col = (col / 3) * 3;

        for(int r = 0; r < 3; r++)
            for(int c = 0; c < 3; c++)
                if(grid[row+r][col+c] == num)
                    return false;

        return true;
    }

    public static boolean fillBoard(int row, int col, int[][] grid)
    {
        if(row==9) {
            row = 0;
            if (++col == 9)
                return true;
        }

        if(grid[row][col] != 0)
            return fillBoard(row+1, col, grid);
        for(int num=1 + (int)(Math.random() * ((9 - 1) + 1)); num<=9; num++)
        {
            if(checkRow(row,num) && checkCol(col,num) && checkBox(row,col,num)){
                grid[row][col] = num;
                if(fillBoard(row+1, col, grid))
                    return true;
            }
        }
        grid[row][col] = 0;
        return false;
    }

    static public void main(String[] args){
        fillBoard(0, 0, grid);
        printGrid();
    }
}

the problem is with generating numbers in fillBoard backtrack algorithm it basically puts 0 everywhere when I change the num range in for loop to 10 it goes smoothly but my numbers need to be lower than 9 i can also change the beginning of backtrack fillBoard to row==8 and col==8 and it fills it correctly with random numbers leaving last row and last column with "0". how to generate random numbers from 1 to 9 and fill all my grid?

4 Answers 4

1

Try this :

public static void main(String[] args) {
    int[][] grid = new int[9][9];
    randomFillGrid(grid, 1, 10);
    for (int[] row : grid) {
        System.out.println(Arrays.toString(row));
    }
}

static void randomFillGrid(int[][] grid, int randomNumberOrigin, int randomNumberBound) {
    PrimitiveIterator.OfInt iterator = ThreadLocalRandom.current()
            .ints(randomNumberOrigin, randomNumberBound)
            .iterator();
    for (int[] row : grid) {
        for (int i = 0; i < row.length; i++) {
            row[i] = iterator.nextInt();
        }
    }
}

EDIT :

if you want to generate a sudoku grid i.e.

the same single integer may not appear twice in the same row, column or in any of the nine 3×3 subregions of the 9x9 playing board.

import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author FaNaJ
 */
public class SudokuGenerator {

    private static final int N = 9;
    private static final int S_N = 3;

    public static int[][] generateSudokuGrid() {
        int[][] grid = new int[N][N];
        int[] row = {1, 2, 3, 4, 5, 6, 7, 8, 9};

        for (int y = 0; y < N; y++) {
            int attempts = 0;

            do {
                if (++attempts > 1000000) { // Oops! I know (sometimes :) it's not a good algorithm...
                    return generateSudokuGrid();
                }
                shuffleArray(row);
            } while (!isAllowed(grid, y, row));

            System.arraycopy(row, 0, grid[y], 0, N);
        }

        return grid;
    }

    static boolean isAllowed(int[][] grid, int y, int[] row) {
        // check columns
        for (int i = 0; i < y; i++) {

            for (int j = 0; j < N; j++) {

                if (grid[i][j] == row[j]) {
                    return false;
                }

            }

        }

        // check sub grids
        int startY = (y / S_N) * S_N;

        for (int x = 0; x < N; x++) {
            int startX = (x / S_N) * S_N;
            for (int j = startX; j < startX + S_N; j++) {
                if (j != x) {

                    for (int i = startY; i < y; i++) {

                        if (grid[i][j] == row[x]) {
                            return false;
                        }

                    }

                }
            }
        }

        return true;
    }

    static void shuffleArray(int[] array) {
        Random random = ThreadLocalRandom.current();
        for (int i = N; i > 1; i--) {
            swap(array, i - 1, random.nextInt(i));
        }
    }

    static void swap(int[] array, int i, int j) {
        int tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
    }

    public static void main(String[] args) {
        int[][] grid = generateSudokuGrid();
        for (int[] row : grid) {
            System.out.println(Arrays.toString(row));
        }
    }

}

output :

[3, 4, 6, 9, 1, 2, 7, 8, 5]
[9, 7, 2, 3, 8, 5, 4, 1, 6]
[5, 8, 1, 6, 7, 4, 3, 2, 9]
[7, 6, 3, 8, 2, 9, 1, 5, 4]
[4, 9, 5, 1, 6, 7, 2, 3, 8]
[2, 1, 8, 4, 5, 3, 6, 9, 7]
[6, 2, 4, 5, 9, 1, 8, 7, 3]
[8, 5, 7, 2, 3, 6, 9, 4, 1]
[1, 3, 9, 7, 4, 8, 5, 6, 2]
Sign up to request clarification or add additional context in comments.

Comments

0

You can use Random class of java.utilpackage to generate random numbers. Below is an example that generates random numbers between 1 to 9:

Random rn = new Random();
int answer = rn.nextInt(9) + 1;

3 Comments

It does generate random, but I need my sudoku board to be unique every time fillBoard() is called. And it has to meet the requirements of sudoku
You can wrap your logic around this to check whether the generated number meets the requirement, if not then you can generate it again. Something like do..while loop will help.
@AndrzejStempnik You didn't include that in your question. You can't expect people to answer properly if your requirements keep changing..
0

Before I start let me say that this while I'm not going tell you outright what all of your errors are, I will help you narrow your search and suggest a method to further debug your code.

Now to your problem: your array populated only with zero.

Only two lines can populate your array. The first sets a spot in the array to have a random int value between 1 and 9 inclusive. If this random number doesn't pass a series of tests then that spot in the array is set to zero.

If one of these testers never returns true, the array will be populated with only zeros.

This leaves 4 functions that could be bugged. -checkRow -checkCol -checkBox -fillBoard

The first 2 functions are relatively simple so I can say with certainty that those work fine.

This leads only the checkBox and fillBoard functions under suspicion as causes of your bug.

At this point, this is where the debugging comes in.

Both of these functions contain loops.

One method to see if your loop is working is to compare a set of expected changes/return values to those which are actually gotten from the program.

To do this, either use a debugger (assert statement + java -ea program.java and or other debugger methods)

Or, you could add print statements within your loop which print your gotten values for various variables/functions.

In any case, welcome to Stacks Overflow.

Comments

0

You mention that you are using a backtrack algorithm so I thought this would be fun to use a backtrack algorithm and try to demonstrate what it is. Below is a mash-up of your code and mine. I tried to stick to what you were doing and only add/change what I felt like I needed to.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * SudokuBoard.
 */
public class SudokuBoard {


    // Dimension size of everything
    static int N = 9;
    // Sudoku grid
    static int[][] grid = new int[N][N];
    // Values that are potentially valid at each position in the sudoku grid
    static int[][][] values = new int[N][N][N];
    // Current index into the values
    static int[][] index = new int[N][N];

    /**
     * Return a shuffled list of values from 1 - 9 with each value       
     * appearing only once.
     */
    private static List<Integer> getValidValues(){
        List<Integer> validValues = new ArrayList<>();
        for(int i = 1; i < 10; i++){
            validValues.add(i);
        }
        Collections.shuffle(validValues);
        return validValues;
    }

    /**
     * Populate the values array with shuffled values to choose from.
     */
    private static void initValues()
    {
        for(int i = 0; i < values.length; i++){
            for(int j = 0; j < values[i].length; j++){
                List<Integer> validValues = getValidValues();
                for(int k = 0; k < values[j].length; k++){
                    values[i][j][k] = validValues.get(k);
                }
            }
        }
    }

    /**
     * print the 2D sudoku grid.
     */
    public static void printGrid()
    {
        for (int row = 0; row < N; row++)
        {
            for (int col = 0; col < N; col++) {
                System.out.printf("%5d", grid[row][col]);
            }
            System.out.println("\n");
        }
    }

    /**
     * Check the row for validity.
     */
    private static boolean checkRow(int row, int num)
    {
        for( int col = 0; col < 9; col++ )
            if(grid[row][col] == num)
                return false;

        return true;
    }

    /**
     * Check the col for validity.
     */
    private static boolean checkCol(int col, int num)
    {
        for( int row = 0; row < 9; row++ )
            if(grid[row][col] == num)
                return false;

        return true;
    }

    /**
     * Check the box for validity.
     */
    private static boolean checkBox(int row, int col, 
                                    int num, boolean testRowCol)
    {
        int theR = row;
        int theC = col;

        row = (row / 3) * 3;
        col = (col / 3) * 3;

        for(int r = 0; r < 3; r++) {
            for (int c = 0; c < 3; c++) {
                if (testRowCol) {
                    if (theR == row + r && theC == col + c){
                        continue;
                    }
                }
                if (grid[row + r][col + c] == num) {
                    return false;
                }
            }
        }

        return true;
    }

    /**
     * Build the sudoku board.
     */
    public static boolean fillBoard(int row, int col)
    {
        // if we are back at the beginning then success!
        // but just for sanity we will check that its right.
        if(row != 0 && col != 0){
            if(row % 9 == 0 && col % 9 == 0){
                return checkBoard();
            }
        }

        // don't go out of range in the grid.
        int r = row % 9;
        int c = col % 9;

        // get the index in the values array that we care about
        int indexIntoValues = index[r][c];

        // if the index is out of range then we have domain wipe out!
        // lets reset the index and try to back up a step. Backtrack!
        if(indexIntoValues > 8){
            index[r][c] = 0;
            // there are a few cases to cover

            // if we are at the beginning and the index is out
            // of range then failure. We should never get here.
            if(row == 0 && col == 0) {
                return false;
            }

            grid[r][c] = 0;

            // if the row is at 0 then back the row up to row - 1 and 
            // the col - 1
            if(r == 0 && c > 0) {
                return fillBoard(row - 1, col - 1);
            }

            // if the row is greater than 0 then just back it up by 1
            if(r > 0){
                return fillBoard(row - 1, col);
            }
        }
        index[r][c] += 1;

        // get the value that we care about
        int gridValue = values[r][c][indexIntoValues];

        // is this value valid
        if(checkRow(r,gridValue) && checkCol(c,gridValue) && 
           checkBox(r,c,gridValue,false)){
            // assign it and move on to the next one
            grid[r][c] = gridValue;
            return fillBoard(row+1, r == 8 ? col + 1 : col);
        }
        // the value is not valid so recurse and try the next value
        return fillBoard(row, col);
    }

    /**
     * This is a sanity check that the board is correct.
     * Only run it after a solution is returned.
     */
    private static boolean checkBoard(){

        //the grid is N X N so just use N as the condition.

        //check rows are ok.
        for(int i = 0; i < N; i++){
            for(int j = 0; j < N; j++){
                //for each of the elements in the row compare against
                //every other one except its self.
                int toTest = grid[i][j];
                //check that the digits in the elements are in the valid range.
                if(toTest > 9 || toTest < 1)
                    return false;
                for(int k = 0; k < N; k++){
                    //don't test me against myself
                    if(k == j)
                        continue;
                    //if i am equal to another in the row there is an error.
                    if(toTest == grid[i][k])
                        return false;
                }
            }
        }

        //check the cols are ok.
        for(int i = 0; i < N; i++){
            for(int j = 0; j < N; j++){
                //flip i and j to go for cols.
                int toTest = grid[j][i];
                for(int k = 0; k < N; k++){
                    if(k == j)
                        continue;
                    if(toTest == grid[k][i])
                        return false;
                }
            }
        }

        //check blocks are ok
        for(int i = 0; i < N; i++){
            for(int j = 0; j < N; j++){
                int toTest = grid[i][j];
                if(!checkBox(i, j, toTest, true))
                    return false;
            }
        }
        return true;
    }

    static public void main(String[] args){
        initValues();
        if(fillBoard(0, 0))
            printGrid();
        else
            System.out.println("Something is broken");
    }
}

So the main things that I added were two multidimensional arrays one is a values list, and the other is a current index into that values list. So the values array keeps a list of all of the valid values that each cell can have. I shuffled the values to give the random feel that you were looking for. We don't really care about value ordering here for any performance reasons, but we want it to be "random" in order to get a different board from run to run. Next the index array keeps track of where you are in the values array. At any point that your index in the index array goes out of bounds, that means that none of the values will work. This is the point that you need reset the index to zero and go back to the cell you came from to try a new value there. That is the backtracking step. I kept moving through the array sequential as you did but its not necessary. I think you could actually go to the variable that has the least amount of valid values, so the highest index in this case, and the search should be faster, but who cares right now, it's a small search, the depth is 81 and you win! I also included a sanity check that the board is valid.

Here is an output:

1    3    2    5    7    6    4    9    8

7    5    8    1    9    4    3    2    6

6    4    9    8    2    3    1    7    5

8    6    3    2    5    9    7    1    4

5    7    4    6    3    1    9    8    2

9    2    1    4    8    7    5    6    3

4    9    7    3    6    8    2    5    1

3    8    5    7    1    2    6    4    9

2    1    6    9    4    5    8    3    7

I hope this helps you in some way, this was a fun one.

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.