SV code for choosing elements from the main array and fixed the sum of those elements

Hi,

I want to write a SV code where from a given array, I want to generate another array with random numbers from the 1st array such that sum of those numbers(2nd array) is always 15. Also, if a value from one index is chosen once, it cannot be chosen again from array1. Here’s the code:

class try;
  int in []='{2,2,3,5,8,10};
  rand bit[5:0] en;
  rand int unsigned sel[];
  
  constraint c1{sel.sum==15;}
  constraint c4{sel.size()==$countones(en);}
  constraint c3{en>0;}
  constraint c2{foreach(in[i]){
    if(en[i]==1){
      sel[sel.sum() with (int'(item>0))]==in[i]; 
    }
  }
  }
  
 endclass

module test;
  
  try t1;
  initial begin;
    t1=new();
    t1.randomize();
    $display("value of en_port =%b and selected ports =%0p",t1.en,t1.sel);
     
  end
endmodule

The issue is that my randomization is failing here. Can you please help me with how to correctly code it?

The problem with your approach is a size constraint on an array must be satisfied before applying any of the initiative constraints on that array. In your example, only certain sizes can match the other constraints but it won’t know that until after the size has been selected.

What you can do is solve for the bits of the en variable and then use post randomized to create the sel array.

class try;
  int in []='{2,2,3,5,8,10};
  rand bit[5:0] en;
  int unsigned sel[$];
  
  constraint c1{
    in.sum() with (en[item.index] ? item : 0) == 15;
  }
  function void post_randomize();
    sel = {};
    foreach (en[i]) if (en[i]) sel.push_front(in[i]);
  endfunction
      
 endclass

module test;
  
  try t1 = new;
  initial repeat(100) begin;
    if (t1.randomize()) 
    $display("value of en_port =%b and selected ports =%0p",t1.en,t1.sel);
     
  end
endmodule