System verilog constraint such that sum of arr[10] is 100 without using .sum method


class sum_method;
rand int arr[10];
constraint c_sum
{
arr[0]+arr[1].......arr[9] == 100;
}
endclass


Is there any better solution for this?

In reply to dve12:

by assuming each array element inside 1-20, we can write below logic

class sum;
   
   rand int list[10];

    constraint C {
         foreach(list[i]) {
	   ( ( i % 2) == 0 ) -> list[i] inside {[1:20]};
	   ( ( i % 2) == 1 ) -> list[i] == 20 - list[i-1];
	 }
    }
endclass

module main;
  initial begin
     sum i_sum = new();
     if ( !i_sum.randomize() ) $display("randomization failed");
     $display(" list = %p sum = %0d", i_sum.list, i_sum.list.sum());
  end
endmodule
1 Like

In reply to Desam:

As gauss said as well, a sum of 10 number is 100 is a each couple returns 20 (you have 5 couples)

class sum#(parameter SUMV=100, parameter NE=10);

rand int unsigned list[NE];

constraint C { foreach(list[i]){
                if(i%2 == 0)
                    list[i]+list[i+1] == 20;
                    }
                };

function void print();
    $display("LIST: %p",list);
    $display("SUM: %d",list.sum());
endfunction

endclass

module main;
initial begin
sum i_sum = new();
if ( !i_sum.randomize() ) $display(“randomization failed”);
i_sum.print();
end
endmodule

I leveraged the previous code sorry for the lack of syntax highlighting
Regards

The other solutions impose addition constraints (element values inside 1 to 20)

You need to define what you want out of a “better solution” than what you provided.

In reply to dve12:


class sum;
 
   rand int list[10];
   rand int arr_t[10]; //helper

    constraint C {
         arr_t[0] == list[0];
         arr_t[9] == 100;
         foreach(list[i]) {
           list[i] inside {[0:100]};
           if(i>0) arr_t[i] == arr_t[i-1] + list[i];
	 }
    }
endclass
 
module main;
  initial begin
     sum i_sum = new();
     if ( !i_sum.randomize() ) $display("randomization failed");
     $display(" list = %p sum = %0d", i_sum.list, i_sum.list.sum());
  end
endmodule



https://www.linkedin.com/in/patel-rahulkumar/