Thursday, July 16, 2020

Generating Sudoko using System verilog constraints


Constraints:
  • c_values : Constraint on minimum and maximum values any element in the matrix can hold
  • c_row_unique :
    • We need to have unique value (from 1 to 9) in each row, for this we run 2 loops
    • Loop - 1 [i,j] iterates through all elements in 2d-matrix
    • Loop - 2 [ ,l] iterates only through each column element
    • If condition is used for not picking up the same element for comparison
  • Constraint c_row_unique and c_col_unique employs similar strategy to generate unique elements in each row and column
  • c_subs_unique :
    • since each sub matrix 3x3 too should have unique values, we can simply divide the i,j and k,l with 3 to pick each 3x3 matrix and apply unique condition for them as well.
    •   !(i==l && j==k) is used to skip same element for comparision.
    • matrix[i][j] != matrix[k][l] , compares one element against all the other elements to avoid replication. 

//------------------------------------------------------------------------------------------------------------------------//

class sudoku;
  rand bit [3:0] matrix[9][9];

  constraint c_values     { foreach (matrix[i,j]) { matrix[i][j] inside {[1:9]}; } }
  constraint c_row_unique { foreach (matrix[i,j]) { foreach (matrix[,l]) { if(j!=l) matrix[i][j] != matrix[i][l]; } } }                    
  constraint c_col_unique { foreach (matrix[i,j]) { foreach (matrix[k,]) { if(i!=k) matrix[i][j] != matrix[k][j]; } } }  

constraint c_sub_unique { foreach (matrix[i,j]) { foreach (matrix[k,l]){ if(i/3 == k/3 && j/3 == l/3 && !(i==k && j==l)) matrix[i][j] != matrix[k][l]; } } } 


  function void display();
    foreach(matrix[i,j]) begin //{
      $write("%0d ",matrix[i][j]);
      if(j == 8) $write("\n");
    end //}
  endfunction: display

endclass: sudoku

module top;
  sudoku s;

  initial begin
    s = new;
    void'(s.randomize());
    s.display();
  end
endmodule:top

No comments:

Post a Comment

Generating prime numbers between 1 to 100

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 class test ; int prime_q[$]; function voi...