-1

Could someone explain how to create a pseudo number generator that has a range of 1 to 51 and can have its value placed within something like the for loop. This has to be in System Verilog and synthesizable. I have read about some CRC and LFSRs but was not quite sure how to modify them to fit it within the specified values I needed (1-52) and how to fit it within a for loop as most examples took up an entire module. Thank you for your time.

initial begin
for(int i = 0; i < 52; i++) begin
  
        int j = // insert PSEUDO RANDOM NUM GEN 0 to 51
  
            if(array[j] == 0)begin
                i = i-1;
                continue;
            end
            else 
            array2[i] = array[j];
             array[j] = 0;
        end
end

(array and array2 both have 52 values of bit size 4)

1 Answers1

0

I don't know what is your application, but what you could do is to generate numbers in the modular ring mod 53 (53 is a prime number). Since you did not mention any other requirement I will take the simplest generator I could imagine, that can be performed without multiplications and will generate numbers, 1 <= n < 52.

function [5:0] next_item(input logic [5:0] v);
  if(v < 26) begin
    next_item = (v << 1); // 2 * v % 53 = 2 * v
  end
  else if(v > 26) begin
    // (2 * v) % 53 = (2 * v - 52 - 1) % 53 = 2 * (v - 26) - 1
    next_item = (((v - 26) << 2) - 1);
  end
  else begin
    // v = 26, you want to exclude 2 * v % 53 = 52, so we skip it
    // by applying the next item again, and it will be 
    next_item = 51;
  end
endfunction

And you could use it like this

parameter SEED = 20; // any number 1 <= N < 52 you like
initial begin
int j = SEED;
for(int i = 0; i < 52; i++) begin
  
      if(array[j-1] == 0)begin
        i = i-1;
        continue;
      end
      else begin
       array2[i] = array[k];
      end
   
      j = next_item(j);
end

Bob
  • 13,867
  • 1
  • 5
  • 27
  • thank you for this, this program was made to create an array of playing card values so a deck of 52 2-9 Ace, Joker, King, and Queen. and then use randomization to randomize values from the first array to the second array. just a question tho when I tried compiling it said "object "param" is not declared" I tried then setting SEED as an int but j always came back as Info "32'sb00000000000000000000000000......" from $display right after the function call, and this is causing an infinite loop. – TonyDaStudent May 03 '21 at 23:57
  • Sorry, I was meant to write `parameter` – Bob May 04 '21 at 12:25