For an associative array can we have a constraint where all its index is odd and the elements at these index are even?
I wrote something like this limiting the size to 10, Is it possible to do it without use of post_randomization?
class odd_index;
randc bit [5:0] idx[10];
rand bit [7:0] array[*];
constraint index {
foreach(idx[i]) {
idx[i] %2 == 1;
}
}
function void post_randomize();
foreach(idx[i]) begin
array[idx[i]] = 2*($urandom_range(0,100));
end
endfunction
endclass
module check;
initial
begin
odd_index o_i = new();
repeat(1) begin
o_i.randomize();
end
$display("%0p\n %0p " ,o_i.idx, o_i.array);
end
endmodule
You cannot modify the number of elements in an associative array with a constraint. You can only modify the number of elements in a dynamic array or queue with a constraint on its size() method.
A better option might be to use pre_randomize().
class odd_index;
rand bit [7:0] array[int];
constraint index {
foreach(array[i]) {
array[i] %2 == 0;
array[i] <=100;
}
}
function void pre_randomize();
bit [7:0] ai;
for(int i=0;i<10;i++) begin
assert(std::randomize(ai) with {
ai % 2 == 1;
ai <= 100;
});
array[ai] = 0;
end
endfunction
endclass
module check;
odd_index o_i = new;
initial
begin
repeat(1) begin
assert(o_i.randomize());
end
$display("%0p " , o_i.array);
end
endmodule
Note: never use the wildcard associative array index [*]–you cannot iterate over the array because a wildcard index has no fixed type.