I am working on trying to build a basic Sudoku generator in java 9+.
The Code works seemingly fine until a random point wherein it stops returning a new number, however the function generating the random number does still produce the numbers as I tested with a log. But it reaches a certain digit and just stops printing. I cannot figure out why. I am very new to algorithms and backtracking so any insight you can provide is appreciated.
Code below
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
class Scratch_5
{
static boolean safe = true;
static int[][] grid = new int[9][9];
public static void main(String[] args)
{
for(int i = 0; i < grid.length; i++)
{
for(int j = 0; j < grid[i].length; j++)
{
int temp = 0;
do
{
temp = getNumber();
}while (!noConflict(grid, i, j, temp));
grid[i][j] = temp;
System.out.print(grid[i][j] + " ");
}
System.out.println();
}
}
static int getNumber()
{
Random r = new Random();
int temp = 0;
temp = r.nextInt(10-0);
return temp;
}
public static boolean noConflict(int[][] array, int row, int col, int num) {
for (int i = 0; i < 9; i++) {
if (array[row][i] == num) {
return false;
}
if (array[i][col] == num) {
return false;
}
}
int gridRow = row - (row % 3);
int gridColumn = col - (col % 3);
for (int p = gridRow; p < gridRow + 3; p++) {
for (int q = gridColumn; q < gridColumn + 3; q++) {
if (array[p][q] == num) {
return false;
}
}
}
return true;
}
}
Thank you.
Your logic is flawed. You will create configurations that cannot be completed, so you will be stuck in the do while loop. Let me demonstrate this with a simple example:
1 2 3 4 5 6 7 8 9
4 5 6 1 2 3 . . .
Any of the positions with a dot cannot be filled, because there is already a 7, 8 or 9 in the box.
You could write a sudoku solver, then you place random numbers in the grid and try to solve it. As soon as there is a unique solution (this can be checked by solving from the bottom, try 1 then 2 then 3 and so on and from the top try 9 first then 8 then 7 and so on, if the 2 solutions are matching it is unique), you have a sudoku (not a solved one as the one you are trying to generate).