To get all the permutations of a set in javascript, you can use a recursive algorithm. Here's one way to implement it:
index.tsx425 chars24 lines
Here's how it works:
getPermutations
function takes an array as input and returns an array of all permutations.permutations
to store the results.swap
to swap two elements in the array.generate
function, which takes an integer n
as input.n
is 1, we have generated a permutation, so we push a copy of the array to permutations
.n-1
elements of the array.generate(n-1)
.n
th element with one of the first n-1
elements, and repeat the process for the remaining n-1
elements.swap
function uses the modulo operator to alternate between swapping the first element and the i-th element for even and odd values of n
.generate
with the length of the input array and return the permutations
array.Here's an example usage:
index.tsx103 chars4 lines
This will output the following array:
index.tsx129 chars9 lines
gistlibby LogSnag