Hi, I would like to describe three methods to generate an ascending array using SystemVerilog constraints. You can generate a descending array via a similar approach.
- Using array sort method
- Using the implication operator
- Assigning a specific value to each element in the array
One way to do it is to generate a random array with unique values. In the post_randomize() function, we can sort the array using sort() method call, and make it an ascending array.
One comment here is that you can obviously write your own sorting methods to do the array sorting. However, the usual bound for sorting is O(nlgn). I highly doubt that the customized sorting methods will have better time efficiency than what’s provided by the vendors.
class c1;
rand bit [4:0] A[]; //dynamic array
//specify array size
constraint c1 {
A.size inside {[8:10]};
}
//generage a unique array
constraint c2 {
unique {A};
}
//sort the array using array method
function void post_randomize ();
A.sort();
endfunction
endclass
c1 c1_h;
initial begin
c1_h = new();
repeat(3) begin
if(c1_h.randomize())
$display("A is %p",c1_h.A);
end
end
endprogram
Another way to do it is to use the implication operator ->. Starting from the second element, we would specify that the current element is larger than the previous one. We have to put a constraint guard here to prevent the out-of-bound value.
class c1;
rand bit [4:0] A[];
//array size
constraint c1 {
A.size inside {[8:10]};
}
//implication operator
constraint c2 {
foreach(A[i])
(i>0)->A[i]>A[i-1]; //constraint guard
}
endclass
c1 c1_h;
initial begin
c1_h = new();
repeat(3) begin
if(c1_h.randomize())
$display("A is %p",c1_h.A);
end
end
endprogram
The last method I can think of is to arbitrarily assign a specific value to each element in the array, which can guarantee the array is in ascending order. For example, we can have A[i] as i, or 2i.
class c1;
rand bit [4:0] A[];
//array size
constraint c1 {
A.size inside {[8:10]};
}
//assign values
constraint c2 {
foreach(A[i])
A[i] == i;
}
endclass
c1 c1_h;
initial begin
c1_h = new();
repeat(3) begin
if(c1_h.randomize())
$display("A is %p",c1_h.A);
end
end
endprogram
Those are the three methods I can think of. Leave me a comment below if you come up with another way to do this. Thanks for reading.
Nice. Thanks for providing 3 ways to generate ascending array
Very Nice example.
Thanks for such example. Please give some more examples