Skip to content

Instantly share code, notes, and snippets.

@mlhaufe
Last active May 12, 2021 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mlhaufe/31c89a46574ae572d84a0e8b780d7b90 to your computer and use it in GitHub Desktop.
Save mlhaufe/31c89a46574ae572d84a0e8b780d7b90 to your computer and use it in GitHub Desktop.
Permutations
// 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')
// 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