Is there an alternative to sum() Constraint

Hi all ,

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 ?


In reply to Have_A_Doubt:

$countones, $onehot, and $isunknown are just shortcuts for $countbits usage.

You could use a foreach loop with a helper unpacked array that is a cascading sum of the previous iteration. I’ll leave that as an exercise for you.

In reply to dave_59:

Hi Dave ,

Thanks for the suggestion .

Here is my code which works


class Sum_Alt ;

        int N ; // Size of Unpacked Arrays !!
        
	int M ; // Sum() of elements !!

   rand bit [3:0] A[] ;  // Need an  alternative to A.sum() !!     

   rand bit [9:0] A_helper[$] ; // Helper Array !!

   constraint SIZE  { A.size() == A_helper.size() ;  A.size() == N ; }
    
   constraint SUM_ALT { 

                            foreach(A_helper[i])
			   {
                              if ( i == 1 )  // When ( i != 0 )
                             {
                                A_helper[i] == A[i] + A[i-1] ;
			     }
			     else if ( i > 1 ) 
                             {
                                A_helper[i] == A[i] + A_helper[i-1] ;
			     }
			     else
                             {
                                A_helper[i] == A[i] ;
			     }
                           }
                       }

     constraint  SUMM  {  A_helper[ A_helper.size() - 1 ]  == M ; }   

  endclass

  Sum_Alt  obj ;

  initial  begin

     obj = new() ;
     obj.N = 4 ; 
     obj.M = 15 ; 

    if ( obj.randomize() )
     begin
       $display("Success with %p",obj);
     end
   else
     $display("Fails"); 

  end


Is there a better way to achieve the Same ?

Yea, convince your instructor that $countones is the best way.