-
Notifications
You must be signed in to change notification settings - Fork 3
/
combinations.js
55 lines (44 loc) · 988 Bytes
/
combinations.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
import {list, range, pick} from '../index.js';
/**
* Yields all combinations of each possible choice of <code>r</code> elements
* of the input iterable.
*
* @example
* // AB AC AD BC BD CD
* combinations('ABCD', 2)
*
* @example
* // 012 013 023 123
* combinations(range(4), 3)
*
* @param {Iterable} iterable - The input iterable.
* @param {Number} r - The size of the combinations to generate.
* @returns {Iterator}
*/
export function* combinations(iterable, r) {
const pool = list(iterable);
const length = pool.length;
if (r > length) {
return;
}
const indices = list(range(0, r, 1));
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] !== i + length - r) {
let pivot = ++indices[i];
for (++i; i < r; ++i) {
indices[i] = ++pivot;
}
break;
}
--i;
}
yield list(pick(pool, indices));
}
}