Array with random numbers from 0 to Size-1 (Without duplicates)

Q) Create an array with all the numbers from 0 to Size - 1 in random order and without duplicates.

Sol: rand bit [3:0] arr;

constraint c1{

arr.size = 6 // For example

foreach(arr[i])
arr[i] = i;

}

void post_randomize()
{
arr.shuffle();
}

Is there any other way to approach this problem?

In reply to Akhil Mehta:

There are several ways. I believe the usage of unique keyword inside constraints would be pretty straightforward.


class test;
  rand bit [2:0] arr[];

constraint c1{

arr.size == 6; // For example

foreach(arr[i])
  arr[i] inside{[0:arr.size()-1]};
 //arr[i] < arr.size();

}
  
  constraint c2{unique{arr};}

function void post_randomize();
  //arr.shuffle();
  
  $display("%0p",arr);
endfunction 

  
  
endclass : test


module top;
  
  test t1;
  
  initial begin
    
    t1 = new;
    t1.randomize();
    
  end
  
endmodule : top

And yeah there are some mistakes in your code. Try to observe them too.

In reply to Shubhabrata:

With some minor adjustments, you can vary the array size when calling randomize:


class test;
  rand bit [2:0] arr[];
  
  constraint arr_size_c {
    soft arr.size == 6;
  };
  
  constraint arr_values_c {
    foreach(arr[i])
      arr[i] inside{[0:arr.size()-1]};
  };
 
  constraint arr_unique_c {
    unique{arr};
  }
 
  function void post_randomize();
    $display("%0p",arr);
  endfunction 
endclass : test

module top;
 
  test t1;
 
  initial begin
    t1 = new;
    for (int i=5; i<=8; i++) begin
      if (!t1.randomize() with {t1.arr.size == i;})
        $display("Randomize failed");
    end
  end
 
endmodule : top

In reply to cgales:

Yes; have familiarity with inline and soft constraints.