Skip to content

Instantly share code, notes, and snippets.

@KEIII
Created April 8, 2023 12:04
Show Gist options
  • Save KEIII/70245805caaab3e53db03d1e859bf169 to your computer and use it in GitHub Desktop.
Save KEIII/70245805caaab3e53db03d1e859bf169 to your computer and use it in GitHub Desktop.
/**
* 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