-
Notifications
You must be signed in to change notification settings - Fork 3
/
combinationswithrepetition.js
56 lines (44 loc) · 1.02 KB
/
combinationswithrepetition.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import {list, nrepeat, pick} from '../index.js';
/**
* Yields all combinations, with repetitions, of each possible choice of
* <code>r</code> elements of the input iterable.
*
* @example
* // A B C
* combinationswithrepetition('ABC', 1)
*
* @example
* // 00 01 02 11 12 22
* combinationswithrepetition(range(3), 2)
*
* @param {Iterable} iterable - The input iterable.
* @param {Number} r - The size of the combinations to generate.
* @returns {Iterator}
*/
export function* combinationswithrepetition(iterable, r) {
const pool = list(iterable);
const length = pool.length;
if (length === 0 && r > 0) {
return;
}
const indices = list(nrepeat(0, r));
yield list(pick(pool, indices));
while (true) {
let i = r - 1;
// eslint-disable-next-line no-constant-condition
while (true) {
if (i < 0) {
return;
}
if (indices[i] !== length - 1) {
const pivot = ++indices[i];
for (++i; i < r; ++i) {
indices[i] = pivot;
}
break;
}
--i;
}
yield list(pick(pool, indices));
}
}