SV Constraint Question

Saw a question : Write a constraint to pick a ball out of 10 different colored balls and that color should not be repeated for the next three draws.
Does my solution below look correct? I am assuming that numbers 1:10 represent the 10 colors.

// Code your testbench here
// or browse Examples



class sample;
 rand int x;
  static int q[$];
  
  
  constraint n_sc{
    x inside {[1:10]};
    q.size()!=0 -> !(x  inside {q});
  }
  
  function void post_randomize();
    q.push_back(x);
    if(q.size()>=4)
      q.pop_front();
    $display("%p",q);
      
  endfunction
endclass
      
      module top;
        
        sample s = new();
        
        initial begin
          repeat(20) begin
            s.randomize();
            $write("%0d,",s.x);
          end
          
        end
      endmodule
        
1 Like

In reply to totochan1985:


class sample;
 rand int x;
  int q[$:2];
 
 
  constraint n_sc{
    x inside {[1:10]};
    unique{x ,q};
  }
 
  function void post_randomize();
    if(q.size() != 3)
       q.push_back(x);    
    else begin 
      q.pop_front();
      q.push_back(x); 
    end   
    $display("%0d %p",x,q);
 
  endfunction
endclass
 
      module top;
 
        sample s = new();
 
        initial begin
          repeat(20) begin
            s.randomize();
            $write("%0d\n",s.x);
          end
 
        end
      endmodule

1 Like