Skip to content

Instantly share code, notes, and snippets.

@danieluhl
Created October 13, 2021 13:21
Show Gist options
  • Save danieluhl/072f612f3dd674443bdc00b07d8550af to your computer and use it in GitHub Desktop.
Save danieluhl/072f612f3dd674443bdc00b07d8550af to your computer and use it in GitHub Desktop.
heaps algorithm in javascript for all permutations O(n!)
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