Created
April 8, 2023 12:04
-
-
Save KEIII/70245805caaab3e53db03d1e859bf169 to your computer and use it in GitHub Desktop.
Permutation https://en.wikipedia.org/wiki/Permutation
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
/** | |
* Generate set of permutations for given length. | |
*/ | |
function* permute(len) { | |
if (len <= 0 || len > 10) throw "argument must be in range 0..10"; | |
function* go(n, permutation, members) { | |
if (n === 0) { | |
yield permutation; | |
} else { | |
for (let index = 0; index < members.length; index++) { | |
const member = members[index]; | |
const rest = members.filter((_, _index) => _index !== index); | |
yield* go(n - 1, [...permutation, member], rest); | |
} | |
} | |
} | |
yield* go( | |
len, | |
[], | |
new Array(len).fill(0).map((_, index) => index) // [0, 1, 2] | |
); | |
} | |
const s = "rgb"; | |
for (const permutation of permute(s.length)) { | |
console.log(permutation.map((i) => s[i]).join("")); | |
} | |
// Will output: | |
// rgb | |
// rbg | |
// grb | |
// gbr | |
// brg | |
// bgr |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment