Skip to content

Instantly share code, notes, and snippets.

@rayhatfield
Created May 2, 2019 20:57
Show Gist options
  • Save rayhatfield/9f55ea66bdc27b5071e3b70b9bc870c3 to your computer and use it in GitHub Desktop.
Save rayhatfield/9f55ea66bdc27b5071e3b70b9bc870c3 to your computer and use it in GitHub Desktop.
generate all permutations of values in javascript
function permutations(values, length = values.length, result = values.map((v) => [v])) {
if (length < 2) {
return result;
}
return permutations(values, length - 1, result.reduce((acc, v) => {
values.forEach((n) => acc.push([...v, n]));
return acc;
}, []));
}
// generate all 4-digit permutations of 1 and 0:
permutations([0, 1], 4);
/*
[0, 0, 0, 0]
[0, 0, 0, 1]
[0, 0, 1, 0]
[0, 0, 1, 1]
[0, 1, 0, 0]
[0, 1, 0, 1]
[0, 1, 1, 0]
[0, 1, 1, 1]
[1, 0, 0, 0]
[1, 0, 0, 1]
[1, 0, 1, 0]
[1, 0, 1, 1]
[1, 1, 0, 0]
[1, 1, 0, 1]
[1, 1, 1, 0]
[1, 1, 1, 1]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment