Search code examples
randomconstraintssystem-veriloguvm

randomizing number of 1's in an array in UVM without using $countones?


In UVM , I want to constraint an array such that I can fix the number of ones in an array to 3, I have written the following code using constraint which uses $countones, but how to do it without using $countones ??

class class_1;
rand bit[31:0] array;

constraint three_ones {
$countones(array) == 3;
}
endclass

Solution

  • What you wrote is equivalent to

    constraint three_ones {
    int'(array[0]) + int'(array[1]) + int'(array[2]) + ... + int'(array[31]) )
       == 3;
    }
    endclass
    

    Update

    To do this programmatically without any functions, you can create another array with a list of indexes that should be set to one. The size of the array is the number of one you want set.

    bit [0:255] array;
    int countones = 5;
    rand int unsigned bitset[]; 
    constraint c_bits { bitset.size == countones;
                        foreach(bitset[i]) bitset[i] inside {[0;$bits(array)-1];
                        unique {bitset};
                      }
    function void post_randomize();
       array = 0;
       foreach(bitset[i]) array[bitset[i]] = 1'b1;
    endfunction
    

    Now there is a way to do this without the unique constraint, and without post_randomize, but that's too much work for me.