Generate a Random Permutation of 1 to n in JavaScript
Last Updated :
01 Apr, 2024
In programming, creating a random permutation of numbers from 1 to n is a common task. A random permutation means randomly rearranging the elements that make up a permutation.
Below are the methods to generate a random permutation of 1 to n in JavaScript:
Fisher-Yates (Knuth) Algorithm
The Knuth shuffle, also called the Fisher-Yates algorithm, is a popular method to generate random permutations. It replaces each element in the array with a previously chosen element at random as it iterates through the array from the last to the first element. This ensures an impartial and effective shuffle.
Example: The function generates a random permutation of numbers from 1 to n using the Fisher-Yates (Knuth) Algorithm.
JavaScript
function generateRandomPermutation(n) {
let permutation = Array
.from({ length: n }, (_, i) => i + 1);
for (let i = n - 1; i > 0; i--) {
const j = Math
.floor(Math.random() * (i + 1));
[permutation[i], permutation[j]]
=
[permutation[j], permutation[i]];
}
return permutation;
}
console.log("Fisher-Yates (Knuth) Algorithm:");
console.log(generateRandomPermutation(5));
OutputFisher-Yates (Knuth) Algorithm:
[ 1, 3, 2, 5, 4 ]
Using Built-in Functions
It is also possible to create a random permutation in JavaScript by combining a random number generator with built-in functions like Array.from() and Array.prototype.sort().
Example: The function generates a random permutation of numbers from 1 to n using built-in functions.
JavaScript
function generateRandomPermutation(n) {
let permutation = Array
.from({ length: n }, (_, i) => i + 1);
permutation
.sort(() => Math.random() - 0.5);
return permutation;
}
console.log("Using Built-in Functions:");
console.log(generateRandomPermutation(5));
OutputUsing Built-in Functions:
[ 3, 1, 4, 2, 5 ]
Share your thoughts in the comments
Please Login to comment...