Programming
Random Number Generation
Algorithms
Integer Arrays
Coding Techniques

Unique random number generation in an integer array

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Generating unique random numbers within an array is a common requirement in programming and mathematical computations. This task involves creating an array such that each number appears exactly once, and each number within the array is randomly chosen from a specified range. This article provides a detailed analysis of the different methods used to achieve this in integer arrays.

Basic Concepts

When generating unique random numbers in an integer array, two constraints must be maintained:

  1. Randomness: The numbers should be placed in a random order.
  2. Uniqueness: Each number should appear just once, without any repetition.

To realize these, several algorithms and methods can be leveraged based on language capabilities and application requirements.

Methods of Generating Unique Random Numbers

1. Fisher–Yates Shuffle

A popular and efficient technique for generating a random permutation of a finite sequence is the Fisher-Yates shuffle algorithm. Here's how it works:

  • Start with a sequential list of integers.
  • Iterate over the list from the last element to the second element.
  • Swap the current element with another randomly chosen element that comes before it or itself.

Example in Python:

  • Time Complexity: O(n)O(n)
  • Space Complexity: O(1)O(1) (in-place shuffle)
  • Initialize the reservoir array with the first `k` elements of the input sequence.
  • Iterate through the remaining elements of the input.
  • For each element `i`, pick a random index `j` from `0` to `i`.
  • If `j` is less than `k`, replace the element in the reservoir with the current element.
  • Time Complexity: O(n)O(n) in the average case
  • Space Complexity: O(n)O(n) due to the additional storage
  • Gaming: Generating diverse random events or map generation.
  • Cryptography: Key generation processes often require random unique sequences.
  • Testing and Simulation: Creating mock datasets or scenarios where various outcomes are tested without bias.

Course illustration
Course illustration

All Rights Reserved.