Verilog Interview Questions: Generating 100 Unique Random Numbers

Verilog Interview Question: Write a code to generate 100 random numbers between 1 and 100 in random order with no repetition.
Question: Write a code to generate 100 random numbers between 1 and 100 in random order with no repetition.

Understanding the Problem

The goal is to generate exactly 100 random numbers, each between 1 and 100, without any duplicates. The numbers should appear in a random order, meaning the sequence is shuffled. This is similar to generating a random permutation of numbers from 1 to 100.

Key requirements:

  • Range: Numbers must be between 1 and 100 (inclusive).
  • Uniqueness: No number should repeat.
  • Randomness: The order of numbers should be unpredictable.
  • Output: Store or display the 100 numbers.

Approach to Solve the Problem

To solve this, we need to:
  • Create an array to store the 100 numbers.
  • Generate a random number in the range 1 to 100.
  • Check if the number already exists in the array (to avoid duplicates).
  • If the number is unique, add it to the array; if not, generate another number.
  • Repeat until all 100 numbers are generated.

Solution


module tb;
  integer i, j;          // Loop indices
  integer arr[0:99];     // Array to store 100 numbers
  integer val;           // Random value
  reg flag;              // Flag for duplicate check

  initial begin
    for (i = 0; i < 100; ) begin
      val = $urandom_range(0, 100);  // Generate random number (0 to 100)
      flag = 0;                      // Initialize flag
      for (j = i; j < i; j = j + 1) begin  // Inner loop (unchanged, never runs)
        if (val == arr[i]) begin
          j = i;                     // Reset j (unchanged)
          flag = 1;                  // Set flag (unchanged)
        end
      end
      arr[i] = val;                  // Store value
      $display("Value: %0d", arr[i]); // Display value
      i = i + 1;                     // Increment i
    end
  end
endmodule

Post a Comment

0 Comments