Randomize deck of cards using constraints

Hi,

I have tried both you and dave’s code, both of them not work correctly.
Your code’s rank will not be unique.
I updated the constraint based on dave’s suggestion and it looks good.



class card;
 rand enum {HEART=0,SPADE,CLUB,DIAMOND} suit;
 rand bit [3:0] rank;
 rand enum {RED=0,BLACK} color;
 
 constraint C_rank {
 	rank inside {[1:13]};
 }
endclass
 
class deck;
	rand card cards[52];
 
	function new ();
		foreach (cards[i])
			cards[i] = new;
	endfunction
 
 
  constraint D {
    foreach(cards[i])
      foreach(cards[j]) {
        if(cards[i].suit == cards[j].suit && i != j)
          cards[i].rank != cards[j].rank;
        if(cards[i].rank == cards[j].rank && i != j)
          cards[i].suit != cards[j].suit;
      }
  
  }
  
  	constraint C_color {
		foreach(cards[i])  {
			( cards[i].suit == card :: HEART || cards[i].suit == card :: DIAMOND) <-> cards[i].color == card::RED;
			( cards[i].suit == card :: SPADE || cards[i].suit == card :: CLUB) <-> cards[i].color == card::BLACK;
		}
	}
  
endclass
 
module test;
        deck one_deck;
        initial begin
          one_deck = new;
          assert (one_deck.randomize());
	  foreach(one_deck.cards[i]) 
	     $display("%p",one_deck.cards[i]);
        end
endmodule