Created
October 13, 2021 13:21
-
-
Save danieluhl/072f612f3dd674443bdc00b07d8550af to your computer and use it in GitHub Desktop.
heaps algorithm in javascript for all permutations O(n!)
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
const swap = (a, b, arr) => { | |
const temp = arr[a]; | |
arr[a] = arr[b]; | |
arr[b] = temp; | |
}; | |
// heaps algorithm | |
const getCombinations = (inputArr) => { | |
const heaps = (result, arr, n) => { | |
n ??= arr.length; | |
if (n === 1) { | |
return result.push([...arr]); | |
} | |
for (let i = 0; i < n - 1; i++) { | |
heaps(result, arr, n - 1); | |
swap(n % 2 ? 0 : i, n - 1, arr); | |
} | |
heaps(result, arr, n - 1); | |
}; | |
const result = []; | |
heaps(result, inputArr); | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment