Created
May 2, 2019 20:57
-
-
Save rayhatfield/9f55ea66bdc27b5071e3b70b9bc870c3 to your computer and use it in GitHub Desktop.
generate all permutations of values in javascript
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
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