Last active
February 25, 2021 14:48
-
-
Save kopiro/771903bfc4678b765206b3b51b12f04a to your computer and use it in GitHub Desktop.
UNIQUE Permutations ES6 Generators
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
const permutations = function*(elements, map = new Map()) { | |
if (elements.length === 1) { | |
yield elements; | |
} else { | |
const [first, ...rest] = elements; | |
for (const perm of permutations(rest, map)) { | |
for (let i = 0; i < elements.length; i++) { | |
const start = perm.slice(0, i); | |
const rest = perm.slice(i); | |
const val = [...start, first, ...rest]; | |
const key = JSON.stringify(val); | |
if (!map.has(key)) { | |
map.set(key, val); | |
yield val; | |
} | |
} | |
} | |
} | |
} |
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
export function* permutations<T>( | |
elements: T[], | |
map: Map<string, T> = new Map(), | |
serializer = (val: T[]) => JSON.stringify(val) | |
) { | |
if (elements.length === 1) { | |
yield elements; | |
} else { | |
const [first, ...rest] = elements; | |
for (const perm of permutations(rest, map, serializer)) { | |
for (let i = 0; i < elements.length; i++) { | |
const start = perm.slice(0, i); | |
const rest = perm.slice(i); | |
const val = [...start, first, ...rest]; | |
const key = serializer(val); | |
if (!map.has(key)) { | |
map.set(key, val); | |
yield val; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment