Given an integer N, the task is to generate N non repeating random numbers.
Input: N = 5
Output: 1 5 2 4 3
Input: N = 8
Output: 7 2 1 8 3 6 4 5
Approach: Create an array of N elements and initialize the elements as 1, 2, 3, 4, …, N then shuffle the array elements using Fisher–Yates shuffle Algorithm.
Fisher–Yates shuffle Algorithm works in O(n) time complexity. The assumption here is, we are given a function rand() that generates random number in O(1) time.
The idea is to start from the last element, swap it with a randomly selected element from the whole array (including last). Now consider the array from 0 to n-2 (size reduced by 1), and repeat the process till we hit the first element.
Below is the implementation of the above approach:
3 4 5 8 6 2 1 7
- Generate a random permutation of elements from range [L, R] (Divide and Conquer)
- C++ program to generate random number
- Program to generate random alphabets
- Implement random-0-6-Generator using the given random-0-1-Generator
- Generating Random String Using PHP
- Binomial Random Variables
- QuickSort using Random Pivoting
- Random Walk (Implementation in Python)
- Select a random number from stream, with O(1) space
- Generate 0 and 1 with 25% and 75% probability
- Select a Random Node from a tree with equal probability
- Select a Random Node from a Singly Linked List
- Random number generator in arbitrary probability distribution fashion
- Generate integer from 1 to 7 with equal probability
- C++ Program for BogoSort or Permutation Sort
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.