Skip to content

Instantly share code, notes, and snippets.

@nicolekc
Created December 10, 2021 01:11
Show Gist options
  • Save nicolekc/5c95a8b77c119090531c247933d9d0e0 to your computer and use it in GitHub Desktop.
Save nicolekc/5c95a8b77c119090531c247933d9d0e0 to your computer and use it in GitHub Desktop.
/**
* Input: 1, 2, 3, 4
* Output:
* 1
* 1, 2
* 1, 2, 3
* 1, 2, 3, 4
* 1, 2, 4
* 1, 3
* 1, 3, 4
* 1, 4
*/
function permutations(input, index = 0, prefix = [], stack = []) {
let next = [ ...prefix, input[index] ];
stack.push(next);
for (let i = index + 1; i < input.length; i++) {
permutations(input, i, next, stack);
}
return stack;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment