Dynamic array sum runs unexpected in constraint

I want to generate an array:
Sum of all array elements must be 17. Array must have at least one element which is multiple of 4. Size of an array can be anything.

My code is:

class fs_array;
  rand bit[4:0] array1[];
   
  constraint c1 { array1.sum() == 17;}
  constraint c2 {array1[0][1:0] == 0;}

   
  function void display();
    $display("array1 = %p",array1);
  endfunction
   
  function void post_randomize();
    array1.shuffle();
  endfunction
endclass

The print is a null array. I commented out post_randomize and constraint c2 and found it is still with the same result. So I think error is from the sum. Can anyone help me how to make it work?

In reply to aaaaaa:



class fs_array;
rand bit[4:0] array1[];

  constraint c1 { 
   array1.size==5; array1.sum() with (int'(item)) == 17;}
   constraint c2 {array1[0][1:0] == 0;}


function void display();
$display("array1 = %p",array1);
endfunction

function void post_randomize();
array1.shuffle();
endfunction
endclass

module tb;
  fs_array f1;
  
  initial begin
    f1 = new();
    if (!f1.randomize) $display ("Error");
    f1.display();
  end
  
  
endmodule


In reply to aaaaaa:


class fs_array;
rand bit[4:0] array1[];
 
  constraint d_size{array1.size==50;array1.sum() == 17;}

  constraint c3{
    array1.sum(item)with(item >0 &int'(item%4 ==0))==1;}
 
 
function void display();
$display("array1 = %p",array1);
endfunction
 
endclass
 
module tb();
  fs_array fs_h;
  initial
       begin
       fs_h =new();
       if(fs_h.randomize())
         fs_h.display();
       end
endmodule

Hope my understanding of your question is correct
Output :-
size = 5 O/P = array1 = '{4, 5, 0, 6, 2}
size=10 O/P=array1 = '{0, 7, 0, 0, 1, 0, 0, 4, 2, 3}
size 50 O/P=array1 = '{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 0, 0, 0, 0, 0, 2, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}

In reply to aaaaaa:

A couple of key points to mention about your example

  • calling randomize() will never change the size of a dynamic array unless its size is constrained. If the array starts out empty it remains empty.
  • The erase size constraints are solved before any of the constraints on the elements. Based on your other constraints on the elements you need at least an array size of two and you probably need to set a reasonable upper bound.
  • by default, the sum() array reduction method uses the size of each element as the size of its result. You need to cast each element to a larger size preventing overflow. See my seminar Verilog Basics for SystemVerilog Constrained Random Verification