Last active
May 12, 2021 14:07
-
-
Save mlhaufe/31c89a46574ae572d84a0e8b780d7b90 to your computer and use it in GitHub Desktop.
Permutations
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
// cyclicPerms(5) | |
// "1,2,3,4,5 | |
// 2,3,4,5,1 | |
// 3,4,5,1,2 | |
// 4,5,1,2,3 | |
// 5,1,2,3,4" | |
const cyclicPerms = (n) => | |
Array.from({length: n},(_,i) => i + 1) | |
.map((_, i, xs) => [...xs, ...xs].slice(i, i+n)) | |
.join('\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
// To interleave x into an array is to return a list of all possible ways of inserting x into it. | |
// interleave("e")(["a", "r"]) => [["e", "a", "r"], ["a", "e", "r"], ["a", "r", "e"]] | |
let interleave = (x) => ([y, ...ys]) => | |
y === undefined ? [[x]] : | |
[[x, y, ...ys], ...interleave(x)(ys).map(i => [y, ...i])] | |
// returns all permutations of the array | |
// perms(['e','r','a']) => [["e", "r", "a"], ["r", "e", "a"], ["r", "a", "e"], ["e", "a", "r"], ["a", "e", "r"], ["a", "r", "e"]] | |
let perms = ([x, ...xs]) => | |
x == undefined ? [[]] : | |
perms(xs).map(interleave(x)).flatMap(t => t) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment