Generate a random permutation of 1 to N - GeeksforGeeks

27 May, 2021
Given an integer N, the task is to generate N non-repeating random numbers.
Examples:  
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 a 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:  
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the next random numberint getNum(vector<int>& v){     // Size of the vector    int n = v.size();     // Generate a random number    srand(time(NULL));     // Make sure the number is within    // the index range    int index = rand() % n;     // Get random number from the vector    int num = v[index];     // Remove the number from the vector    swap(v[index], v[n - 1]);    v.pop_back();     // Return the removed number    return num;} // Function to generate n non-repeating random numbersvoid generateRandom(int n){    vector<int> v(n);     // Fill the vector with the values    // 1, 2, 3, ..., n    for (int i = 0; i < n; i++)        v[i] = i + 1;     // While vector has elements    // get a random number from the vector and print it    while (v.size()) {        cout << getNum(v) << " ";    }} // Driver codeint main(){    int n = 8;    generateRandom(n);     return 0;}
// Java implementation of the approachimport java.util.*;import java.lang.Math; class GfG{     // Function to return the next random number    static int getNum(ArrayList<Integer> v)    {        // Size of the vector        int n = v.size();             // Make sure the number is within        // the index range        int index = (int)(Math.random() * n);             // Get random number from the vector        int num = v.get(index);             // Remove the number from the vector        v.set(index, v.get(n - 1));        v.remove(n - 1);             // Return the removed number        return num;    }         // Function to generate n    // non-repeating random numbers    static void generateRandom(int n)    {        ArrayList<Integer> v = new ArrayList<>(n);             // Fill the vector with the values        // 1, 2, 3, ..., n        for (int i = 0; i < n; i++)            v.add(i + 1);             // While vector has elements        // get a random number from the vector and print it        while (v.size() > 0)        {            System.out.print(getNum(v) + " ");        }    }     // Driver code    public static void main(String []args)    {                 int n = 8;        generateRandom(n);    }} // This code is contributed by Rituraj Jain
# Python3 implementation of the approach # import random moduleimport random # Function to return the next# random numberdef getNum(v) :     # Size of the vector    n = len(v)     # Generate a random number within    # the index range    index = random.randint(0, n - 1)     # Get random number from the vector    num = v[index]     # Remove the number from the vector    v[index], v[n - 1] = v[n - 1], v[index]    v.pop()     # Return the removed number    return num # Function to generate n non-repeating# random numbersdef generateRandom(n) :         v = [0] * n     # Fill the vector with the values    # 1, 2, 3, ..., n    for i in range(n) :        v[i] = i + 1     # While vector has elements get a     # random number from the vector    # and print it    while (len(v)) :        print(getNum(v), end = " ") # Driver codeif __name__ == "__main__" :         n = 8    generateRandom(n)     # This code is contributed by Ryuga
// C# implementation of the approachusing System;using System.Collections; class GfG{  // Function to return the next random numberstatic int getNum(ArrayList v){         // Size of the vector    int n = v.Count;         Random rand = new Random();         // Make sure the number is within    // the index range    int index = (rand.Next() % n);      // Get random number from the vector    int num = (int)v[index];      // Remove the number from the vector    v[index] = (int)v[n - 1];    v.Remove(v[n - 1]);      // Return the removed number    return num;}  // Function to generate n// non-repeating random numbersstatic void generateRandom(int n){    ArrayList v = new ArrayList(n);         // Fill the vector with the values    // 1, 2, 3, ..., n    for(int i = 0; i < n; i++)        v.Add(i + 1);      // While vector has elements get a    // random number from the vector    // and print it    while (v.Count > 0)    {        Console.Write(getNum(v) + " ");    }} // Driver codepublic static void Main(string []args){    int n = 8;         generateRandom(n);}} // This code is contributed by rutvik_56
<?php// PHP implementation of the approach // Function to return the next random numberfunction getNum(&$v){     // Size of the vector    $n = sizeof($v);     // Generate a random number    srand(time(NULL));     // Make sure the number is within    // the index range    $index = rand() % $n;     // Get random number from the vector    $num = $v[$index];     // Remove the number from the vector    $t = $v[$index];    $v[$index] = $v[$n - 1];    $v[$n - 1] = $t;    array_pop($v);     // Return the removed number    return $num;} // Function to generate n non-repeating// random numbersfunction generateRandom($n){    $v = array(0, $n, NULL);     // Fill the vector with the values    // 1, 2, 3, ..., n    for ($i = 0; $i < $n; $i++)        $v[$i] = $i + 1;     // While vector has elements    // get a random number from the    // vector and print it    while (sizeof($v))    {        echo getNum($v) . " ";    }} // Driver code$n = 8;generateRandom($n); // This code is contributed by ita_c?>
<script>// Javascript implementation of the approach // Function to return the next random numberfunction getNum(v){        // Size of the vector        let n = v.length;              // Make sure the number is within        // the index range        let index = Math.floor(Math.random() % n);                  // Get random number from the vector        let num = v[index];              // Remove the number from the vector        v[index] = v[n - 1];        v.splice(n - 1,1);              // Return the removed number        return num;} // Function to generate n// non-repeating random numbersfunction generateRandom(n){        let v = [];              // Fill the vector with the values        // 1, 2, 3, ..., n        for (let i = 0; i < n; i++)            v.push(i + 1);              // While vector has elements        // get a random number from the vector and print it        while (v.length > 0)        {            document.write(getNum(v) + " ");        }} // Driver codelet n = 8;generateRandom(n);  // This code is contributed by rag2127</script>
3 4 5 8 6 2 1 7
 
ankthon
ukasp
rituraj_jain
rutvik_56
rag2127
C++ Programs
Randomized
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Program for QuickSort
cin in C++
delete keyword in C++
CSV file management using C++
Shallow Copy and Deep Copy in C++
QuickSort using Random Pivoting
K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)
Shuffle or Randomize a list in Java
Estimating the value of Pi using Monte Carlo
Random Walk (Implementation in Python)