Last active
July 15, 2022 13:25
-
-
Save xxzefgh/87cdcce6b05317d2286669fa70d869e2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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