Generic Sudoku Using Randomization

In reply to Etrx91:

Hi,

you can find the below logic that contains constraints for solving sudoku puzzle with 9 * 9 size. you can use this logic to come with a generic logic for other sizes as well. Please find the below code.



class sudoku;
	rand int unsigned item[9][9];
	int unsigned problem[9][9];     // the problem data (9*9 matrix with 0 in the blank spaces)
	constraint c1{foreach(item[i,j])              
				item[i][j] inside {[1:9]};}
	
	constraint c2{foreach(item[i,j])   // this constraint is for getting unique elements in each row
				foreach(item[,k])
					if(j != k)
						item[i][j] != item[i][k];}
	
	constraint c3{foreach(item[i,j])    // this constraint is for getting unique elements in each column 
				foreach(item[k,])
					if(i != k)
						item[i][j] != item[k][j];}
					
	constraint c4{foreach(item[i,j])    // this constraint is for getting unique elements in each matrix of 3 * 3
				foreach(item[k,l])
					if((i/3 == k/3)&&(j/3 == l/3)&&(i!=k)&&(j!=l))
						item[i][j]!=item[k][l];}
	
	constraint c5{foreach(item[i,j])
				if(problem[i][j] != 0)
					item[i][j] == problem[i][j];}
						
	function int get_solution(int unsigned prob[9][9]);
		problem = prob;
		return this.randomize();
	endfunction
	
	function void print();
		int k,l;
		$display("\n\n");
		for(int i=0; i<9; i++)
			begin
				for(int j=0; j<9; j++)
					begin	
						$write(" %0d", this.item[i][j]);
						l++;
						if(l%3 == 0)
							$write(" ");
					end
				$display("");
				k++;
				if(k%3 == 0)
					$display("");
			end
		$display("\n\n");
	endfunction
endclass