I'm trying to make a valid 9 X 9 sudoku set. I tried it by making blocks of 3X3 and checking for the rules of sudoku on the way as i made other blocks. The code works for like 4 blocks(sometimes 1) and then it freezes. Need help.
import java.util.Random;
public class wtf {
/**
* @param args
*/
public static void main(String[] args) {
int[] check;
check = new int[9];
int [][] sudoku;
sudoku= new int[10][10];
int i, j, k=0, z, t=0;
boolean c=true;
Random no = new Random();
for (int cellc=0; cellc<3; cellc++){
for (int cellh=0; cellh<3; cellh++){
clear(check, 9);
t=0;
for (i=3*cellc; i<=(3*cellc+2); i++){
for (j=3*cellh; j<=(3*cellh+2); j++){
for(c=true; c==true;){
z = no.nextInt(9)+1;
c=linearSearch(check, 9, z);
if ((c==true) || (vertical(sudoku, z, j)==true) || (horizontal(sudoku, z, i)==true))
{
c=true;
continue;
}
check[t]=z;
t++;
sudoku[i][j]=z;
}
}
}
psudo(sudoku);
}
}
// TODO Auto-generated method stub
}
public static boolean linearSearch(int[] a, int upto, int key) {
for (int i = 0; i < upto; i++) {
if (key == a[i]) {
return true; // Found key, return index.
}
}
return false; // Failed to find key
}
public static void clear(int [] a, int upto)
{
for (int i = 0; i < upto; i++)
{
a[i]=0;
}
}
public static boolean vertical(int[][] sudoku, int a, int column)
{
for (int i = 0; i < 9; i++) {
if (a == sudoku[i][column]) {
return true;
}
}
return false;
}
public static boolean horizontal(int [][]sudoku, int a, int row)
{
for (int i = 0; i < 9; i++) {
if (a == sudoku[row][i]) {
return true;
}
}
return false;
}
public static void psudo(int[][] sudoku)
{int i,j;
for (i=0; i<=8; i++){
for (j=0; j<=8; j++){
System.out.print(sudoku[i][j]+ " ") ;
}
System.out.println();
}
}
}