Dynamic Array in ascending order with sum of elements

HI All,

Question_1 : I want to have the numbers in ascending order with sum of the elements must be less than 10.
But getting randomization failure, could you please suggest?

module p1;
  class c1;
    rand bit [3:0] addr[];
   constraint c1{
    addr.size == 6;
     foreach(addr[m])
     (m>0) -> addr[m]> addr[m-1];
     addr.sum() with (int'(item))<10;
       }
    function void post_randomize();
    $display("elements %0p", obj);
    endfunction
  endclass
  c1 obj;
  initial begin
    obj = new;
    repeat (2)
    obj.randomize();
  end
endmodule

Question_2 :
There is a dynamic array with elements of ascending order, with each element being in the range of 1:20 and whose sum should be less than 100.
Here, length of the dynamic array is not given, need to extract from this question. How to do this??

My opinion : The minimum value for each element is 1, so it can 1111111…99(1’s)
I can say max size is 99.
But

foreach(array[m])
array[m] inside {[1:20]}

It cannot always have 1…1.1…, it can vary from 1 to 20.
So not having any clue to find the size of the dynamic array in this requirement.
Could you help me?

Kindly suggest for Question1 and Question2

Thank you,

module p1;
  class c1;
    rand bit[3:0] addr[  ];
    constraint c1 {
      addr.size == 6;
      foreach(addr[m])
        (m > 0) -> addr[m] >= addr[m-1];
      addr.sum() with (int'(item)) < 10;
    }
    function void post_randomize();
      $display("elements %0p", addr);
    endfunction
  endclass
  c1 obj;
  initial begin
    obj = new;
    repeat (2)
      obj.randomize();
  end
endmodule

here, your sum of array is less than 10.But you wrote, addr[m]>addr[m-1] ,it’s simply not possible. So i made addr[m]>=addr[m-1] now it’s working properly.

HI @Surya_prakash.Kapireddy

Thanks for the reply, yes its working. I can see this output

xcelium> run
elements ‘{addr:’{'h0, 'h0, 'h1, 'h2, 'h2, 'h4}}
elements ‘{addr:’{'h0, 'h1, 'h1, 'h2, 'h2, 'h2}}

Some elements are repeating, I think I can make array.uniqe in post_randomization.

Thank you

I’d recommend to split your requirements into 2 steps:
First write a constraint which meetes sum > 10.
Secondly you can sort your array in the right order using the sort method of the array. This can be done in the post_randomize function.

You first question is unsolvable–you have conflicting constraints.
The smallest set of ascending numbers in an array of 6 elements is

0+1+2+3+4+5 = 15

The constraint foreach(addr[m]) (m>0) -> addr[m]> addr[m-1]; specifies they must be in ascending order and must be unique.

You need to clarify your second question. If the max size of the dynamic array is 99, and each element can have a minimum value of 1, then the sum can easily be less than 100. But if each element needs to be unique, and only in the range [1:20], you can have at most 20 elements, and their sum needs to be 210.

Thank you Dave for the detailed info.