Constraint #38
Constraints can be applied to a 2-dimensional array to form a lower triangular matrix, as shown below:
5? 0? 0? 0
5? 5? 0? 0
5? 5? 5? 0
5? 5? 5? 5
In this matrix, each row has one more non-zero element than the previous row, and all elements above the main diagonal are zero. To implement this constraint, we can use a 2-dimensional array with a size of 4x4.
rand bit[8:0] array[3:0][3:0];
We iterate through the array using two indices,
i for the row and j for the column. The value in each cell depends on the relationship between i and j.
For the first row, i=0, and only the element at (0,0) should be 5, with all other elements being 0.
For the second row, i=1, elements at (1,0) and (1,1) should be 5, with all other elements being 0.
For the third row, i=2, elements at (2,0), (2,1), and (2,2) should be 5, with all other elements being 0.
Based on the observation, when I <= j, the value is 5. Else 0
To write the constraint for the lower triangular matrix pattern, we need to use two foreach loops. Like Mentioned below
foreach(array[i]) { ????????? foreach(array[i]) {? ???????? // condition } }
we can use a single foreach loop with two variables. The condition for the value assignment is such that when j ≤ i, the value should be 5, otherwise 0.
领英推荐
??? foreach (array[i,j]) {
??????? if (i >= j) ???array[i][j] == 5;
??????? else ??????????array[i][j] == 0;
??????? }
This constraint ensures the array forms a lower triangular matrix with the specified pattern.
class sample;
rand bit[7:0] array[0:3][0:3];
constraint array_c {
foreach(array[i,j]){
if(j<=i) {
array[i][j] == 5;
}
else array[i][j] == 0;
}
}
endclass
module top;
sample s=new();
initial begin
$display("######## OUTPUT ########");
assert(s.randomize());
foreach(s.array[i,j]) begin
$write("%0d \t",s.array[i][j]);
if(j==3)
$display("");
end
$display("######## END ########");
end
endmodule
I appreciate your understanding of the methodology we've utilized to handle constraints and their real-world applications. Your support, through likes and reposts, will indeed encourage further exploration. I'm eagerly looking forward to engaging in meaningful discussions with you. Thank you! ????
Let's Break Down the Above Constraint:
In Class
In Module Top
This program generates random 2D arrays with specific patterns of elements based on the constraints specified. The output displays the generated 2D array in a tabular format for better understanding.