I'm trying to make a sudoku generator so I can make into a sudoku game and I've encountered a problem... I have successfully made a method which checks a certain cell and whether the number in it repeats in the same row, column or 3x3 square it belongs to but I have a problem with generating the numbers randomly and filling them in. Basically first I fill the first line with random numbers from 1-9 which only appear once in the line. My question is, is it possible to fill cell after cell with random numbers which suit the numbers generized so far or should I fill line by line? Or maybe square by square? Because my loop seems to turn into an infinite loop. Here's the code:
package test;
import java.util.Random;
public class Test {
public static void main(String[] args) {
int[][]test=new int[9][9];
int[]prva=new int[]{1,2,3,4,5,6,7,8,9};
zapolniPrvo(test,prva);//fills the first line of the table
print(test);
System.out.println();
int y=1;
int x=0;
int rn=0;
int a=1;
for(int i=1;i<9;i++){
for(int j=0;j<9;j++){
while(!razlicnostT(j,i,test)){
test[i][j]=(int)(Math.random()*9+1);
}
}
}
print(test);
}
public static boolean razlicnostT(int y,int x,int[][]test){ //checks for same number in the line, row and square
int vrstica=0;
int kolona=0;
int yy=(y/3)*3;
int xx=(x/3)*3;
int yyy=(y%3);
int xxx=(x%3);
int kvadrat=0;
boolean razlicnost=false;
for(int i=yy;i<=yyy;i++){
for(int j=xx;j<=xxx;j++){
if(test[i][j]==test[y][x]){
kvadrat++;
}
}
}
for(int i=0;i<x;i++){
if(test[y][i]!=test[y][x]){
vrstica++;
}
}
for(int i=0;i<y;i++){
if(test[i][x]!=test[y][x]){
kolona++;
}
}
if((vrstica==x) && (kolona==y)&&(test[y][x]!=0)&&(kvadrat!=1)){
razlicnost=true;
} else {
razlicnost=false;
}
return razlicnost;
}
public static void zapolniPrvo(int[][]test,int[]prva){
randomize(prva);
for(int i=0;i<9;i++){
test[0][i]=prva[i];
}
}
public static void print(int[][]test){
for(int i=0;i<test.length;i++){
for(int j=0;j<test.length;j++){
System.out.print(test[i][j]+" ");
}
System.out.println();
}
}
public static void randomize (int[]temp){
Random rnd = new Random();
for (int i = temp.length - 1; i > 0; i--){
int index = rnd.nextInt(i + 1);
int a = temp[index];
temp[index] = temp[i];
temp[i] = a;
}
}
}
Note: razlicnostT returns true if the number appears only once in the row/column/3x3 square and test is the table