I was recently asked an alternative to $countones( a ) == N ;
rand bit [9:0] a ;
bit [3:0] N ; // a can have Max 10 Ones !!
// constraint CCOUNTONES { $countones( a ) == N ; } // Need an Alternative for this
I came up with 2 solutions ::
(1) $countbits() Function
(2) Random helper Unpacked array and using sum() .
Is there any other Solution possible ?
Is there an alternative to sum() Constraint ?
rand bit [3:0] A [ 4 ] ;
// constraint SUM { A.sum() == 10 ; } // Any alternative to this ?
I am trying to use helper int variable rather than array for cascading sum inside constraint(while simulation it troughing an error) could you please tell me what’s wrong in this approach?
I observe 2 compilation issues whereas randomization failure is observed at run-time
a) rand unsigned int current_sum; // Should be rand int unsigned current_sum;
b) Operator += is illegal in constraint as it has assignment operator '=' in it's equivalent expression
Constraints are essentially expressions and not assignment statements
(2) Constraints are not procedural in nature. They are solved in parallel.
Here is a small homework for you
class Class;
rand int unsigned current_sum;
rand int arr[50];
constraint sum_constraint {
foreach (arr[i])
{
arr[i] inside {[0:100]};
current_sum == current_sum + arr[i]; // Constraints are expressions
}
//current_sum == 100; // Commented out the conflict
}
endclass
Observe the output and try to understand the reason behind it.