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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Implement random-0-6-Generator using the given random-0-1-Generator
- Select a random number from stream, with O(1) space
- Random number generator in arbitrary probability distribution fashion
- Select a Random Node from a Singly Linked List
- Binomial Random Variables
- Random Walk (Implementation in Python)
- QuickSort using Random Pivoting
- Select a Random Node from a tree with equal probability
- Generating Random String Using PHP
- Random Numbers Ecosystem in Julia - The Natural Side
- Find N random points within a Circle
- Generate integer from 1 to 7 with equal probability
- Generate 0 and 1 with 25% and 75% probability
- Program to generate CAPTCHA and verify user
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.