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
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Generate a random permutation of elements from range [L, R] (Divide and Conquer)
- Program to generate random alphabets
- C++ program to generate random number
- Implement random-0-6-Generator using the given random-0-1-Generator
- Binomial Random Variables
- QuickSort using Random Pivoting
- Generating Random String Using PHP
- Random Walk (Implementation in Python)
- Generate 0 and 1 with 25% and 75% probability
- Select a random number from stream, with O(1) space
- Random Numbers Ecosystem in Julia - The Natural Side
- Select a Random Node from a tree with equal probability
- Select a Random Node from a Singly Linked List
- Generate integer from 1 to 7 with equal probability
- Random number generator in arbitrary probability distribution fashion
- Program to generate CAPTCHA and verify user
- C++ Program for BogoSort or Permutation Sort
- Generate a number such that the frequency of each digit is digit times the frequency in given number
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.