Skip to content

Instantly share code, notes, and snippets.

@xxzefgh
Last active July 15, 2022 13:25
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 xxzefgh/87cdcce6b05317d2286669fa70d869e2 to your computer and use it in GitHub Desktop.
Save xxzefgh/87cdcce6b05317d2286669fa70d869e2 to your computer and use it in GitHub Desktop.
function repeat(x: number, n: number): number[] {
return Array(n).fill(x);
}
/**
* Reimplemented Python's itertools.combinations_with_replacement
* https://docs.python.org/3/library/itertools.html#itertools.combinations_with_replacement
*/
export function* combinationsWithReplacement<T>(pool: T[], r: number) {
const n = pool.length;
if (!(n && r)) {
return;
}
const indices = repeat(0, r);
yield indices.map((i) => pool[i]);
while (true) {
let cont = false;
let i = r - 1;
for (; i >= 0; i--) {
if (indices[i] !== n - 1) {
cont = true;
break;
}
}
if (!cont) {
return;
}
indices.splice(i, r - i, ...repeat(indices[i] + 1, r - i));
yield indices.map((i) => pool[i]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment