Constraints: for a N bit vector generate all M bit set combinations

Hi,

For a N bit vector I want to generate all combinations with M bits set.


module nmbits;
    parameter N = 4;
    parameter M = 2;

    class temp;
        rand bit [N-1:0] val;
        bit [N-1: 0] val_q[$];
    
        constraint val_c {
            $countones(val) == 2;
            unique {val, val_q};
        }

        function void post_randomize();
            val_q.push_back(val);
        endfunction: post_randomize 

        function gen_val();
            for (int i=0; i<2**N; i++) begin 
                assert(this.randomize); $display("%d",val);
            end
            foreach(val_q[j]) $display("val_q[%0d]: %b", j, val_q[j]);
        endfunction: gen_val 
    endclass: temp 

    initial begin 
        temp    mn = new;
        assert(mn.randomize);
        mn.gen_val();
    end

endmodule: nmbits


Is there a better way of implementing this?

Thanks

In reply to nnd:

You could directly declare val as ‘randc’


module nmbits;
    parameter N = 4;
    parameter M = 2;
 
    class temp;
        randc bit [N-1:0] val;
        
 
        constraint val_c {
            $countones(val) == M; // Typo in your code here !!
                          }
 
        
        
    endclass: temp 
    
    temp    mn ;

    initial begin 

        mn = new;
       
      for (int i=0; i<2**N; i++) begin  
          if (mn.randomize); $display("For %0d :: %d i.e %4b",i,mn.val,mn.val);
            end
    end
 
endmodule: nmbits

In reply to ABD_91:

The problem with randc is that number of outcomes is limited so i get constraint errors in the for loop.

In reply to nnd:

I don’t see any issue with the code I posted .
With or without randc for a 4-bit ‘val’ , you Should see 6 Unique Possibilities .