class A;
rand bit[4:0] array[10];
rand bit[4:0] num1,num2;
constraint C1 { foreach(array[i]) foreach(array[j]) {if(i!=j) array[i]!= array[j];}}
constraint C2 {num1 !=num2; num1<10;num2<10;}
function void post_randomize();
$display("post_randomize: num1=%d, num2=%d",num1,num2);
array[num1]=array[num2];
endfunction
function print();
foreach(array[i]) begin
$display("arr[%d]=%d",i,array[i]);
foreach(array[j])
if(array[i]==array[j] && i!=j) $display("array[%d] and array[%d] matches",i,j);
end
endfunction
endclass
module tb;
A a=new();
initial begin
assert(a.randomize());
a.print();
end
endmodule
In reply to burra thanuja:
Bellow is simple sollution i have written for the above problem
class my_rand;
rand bit [5:0] a[10];
rand int b,c;
constraint sum_new {
solve b,c before a;
foreach(a[i]){
if((i == b )|| (i==c) )
(a.sum() with(int'((item == a[i]))) ) == 2;
else
(a.sum() with(int'((item == a[i]))) ) == 1;
}
}
constraint n1{
b inside {[0:9]};
c inside {[0:9]};
c != b;
}
endclass
module mod ();
initial
begin
my_rand me;
me = new();
me.randomize();
$display("%p",me.a);
end
endmodule
You can get the address question with below code.
It’s working 100%.
Array = '{'h0, 'h1, 'h2, 'h2, 'h3, 'h6, 'h7, 'h8, 'hb, 'he}
class ABC;
rand bit [3:0] array[10];
constraint a_c {
foreach(array[i]) {
if(i>0) {
if(i == 3)
array[i] == array[i-1];
else
array[i] > array[i-1];
}
}
}
endclass
module tb;
initial begin
ABC abc;
abc = new();
abc.randomize();
$display("Array = %p", abc.array);
end
endmodule
Here is performance friendly array randomization with 10 unique element values. In all above discussions, wherever we are using 2 foreach loops can be replaced with below code
class optimized_unique_array;
rand int array[10];
localparam int RANGE_START = 1;
localparam int RANGE_END = 100;
// Static pool created once and reused
static int pool[RANGE_END-RANGE_START+1];
static bit pool_initialized = 0;
function void pre_randomize();
if (!pool_initialized) begin
foreach (pool[i]) pool[i] = RANGE_START + i;
pool_initialized = 1;
end
endfunction
function void post_randomize();
pool.shuffle(); // Shuffle the existing pool
array = pool[0:array.size()-1]; // Take first N elements
endfunction
endclass