I have been asked to randomize a dynamic array with unique values with following conditions
- Unique key word can’t be used
- Use pre and post randomize functions
- Can not use foreach or any other loops in constraint
I have been asked to randomize a dynamic array with unique values with following conditions
In reply to bachan21:
class A;
typedef bit [2:0] number_t;
rand number_t number;
number_t recent_numbers[$];
bit add;
function void post_randomize();
add = 1;
foreach (recent_numbers[i]) begin
if (recent_numbers[i] == number) begin
add = 0;
break;
end else begin
add = 1;
end
end
if (add == 1) begin
recent_numbers.push_front(number);
end
if (recent_numbers.size() > 5)
void'(recent_numbers.pop_back());
endfunction
endclass : A
module top();
A a = new();
initial begin
repeat(10) begin
if(!a.randomize()) $display("Please look into randomization issue");
if (a.recent_numbers.size() == 5) begin
$display("recent_numbers = %p",a.recent_numbers);
end
end
end
endmodule : top
In reply to megamind:
Hi,
Can you explain your code, because I cant find the declaration of any dynamic array
In reply to bachan21:
I have used queue , instead of dynamic array , if you use dynamic array then syntax will change for adding elements , nothing much in the logic should change. Does it make sense ?
In reply to megamind:
Yeah I got your logic.
You are randomizing the value and adding to the queue by randomizing for 10 times.
But can we modify the logic such that a dynamic array can be used instead of queue?
In reply to bachan21:
class A;
typedef bit [2:0] number_t;
number_t recent_numbers[];
function void post_randomize();
recent_numbers = new[5];
foreach (recent_numbers[i]) begin
recent_numbers[i] = i;
end
endfunction : post_randomize
endclass : A
module top();
A a = new();
initial begin
repeat(1) begin
if(!a.randomize()) $display("Please look into randomization issue");
$display("----->> recent_numbers = %p \n",a.recent_numbers);
end
end
endmodule : top
In reply to megamind:
class A;
typedef bit [31:0] number_t;
number_t recent_numbers;
bit [16:0] random_num;
function void post_randomize();
recent_numbers = new[5];
foreach (recent_numbers[i]) begin
recent_numbers[i] = i;
end
recent_numbers.shuffle();
random_num = $urandom();
$display("random_num = %0d ",random_num);
foreach (recent_numbers[i]) begin
recent_numbers[i] = recent_numbers[i] + random_num;
end
endfunction : post_randomize
endclass : A
module top();
A a = new();
initial begin
repeat(10) begin
if(!a.randomize()) $display(“Please look into randomization issue”);
$display(" >>> Recent_numbers = %p \n\n",a.recent_numbers);
end
end
endmodule : top