Created
October 19, 2017 01:35
-
-
Save tonymtz/543444545511724f65b39ff4272afb4f to your computer and use it in GitHub Desktop.
Calculates all permutations for a given array of elements following Heap's Algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Calculates all permutations for a given array of elements following Heap's Algorithm | |
// how to use it... | |
console.log(generatePermutations([1, 2])); | |
console.log(generatePermutations([1, 2, 3])); | |
console.log(generatePermutations([1, 2, 3, 4, 5, 6, 7, 8, 9])); | |
function generatePermutations(inputArray) { | |
let output = []; | |
generate(inputArray.length, inputArray); | |
return output; | |
function generate(elementsNumber, array) { | |
if (elementsNumber === 1) { | |
return output.push(array.slice(0, array.length)); | |
} else { | |
for (let i = 0; i < elementsNumber - 1; i += 1) { | |
generate(elementsNumber - 1, array); | |
if (elementsNumber % 2 === 0) { | |
swap(i, elementsNumber - 1, array); | |
} else { | |
swap(0, elementsNumber - 1, array); | |
} | |
} | |
generate(elementsNumber - 1, array); | |
} | |
} | |
function swap(x, y, array) { | |
let z = array[x]; | |
array[x] = array[y]; | |
array[y] = z; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment