-
Notifications
You must be signed in to change notification settings - Fork 31
/
combinations.ts
67 lines (63 loc) · 1.37 KB
/
combinations.ts
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
57
58
59
60
61
62
63
64
65
66
67
/* eslint-disable no-constant-condition */
/**
* 遍历所有大小为`r`的组合.
* @param n 元素总数.
* @param r 选取的元素个数.
* @param f 回调函数, 用于处理每个组合的结果.返回`true`时停止遍历.
* @example
* ```ts
* enumerateCombinations(4, 2, comb => {
* console.log(comb)
* })
* // [ 0, 1 ]
* // [ 0, 2 ]
* // [ 0, 3 ]
* // [ 1, 2 ]
* // [ 1, 3 ]
* // [ 2, 3 ]
* ```
* @complexity C(30,10)(3e7) => 170ms.
*/
function enumerateCombinations(
n: number,
r: number,
f: (indicesView: readonly number[]) => boolean | void
): void {
const ids = Array.from({ length: r }, (_, i) => i)
if (f(ids)) {
return
}
while (true) {
let i = r - 1
for (; i >= 0; i--) {
if (ids[i] !== i + n - r) {
break
}
}
if (i === -1) {
return
}
ids[i]++
for (let j = i + 1; j < r; j++) {
ids[j] = ids[j - 1] + 1
}
if (f(ids)) {
return
}
}
}
export { enumerateCombinations }
if (require.main === module) {
enumerateCombinations(4, 2, comb => {
console.log(comb)
})
const n = 30
const r = 10
console.time('enumerateCombinations')
let count = 0
enumerateCombinations(n, r, () => {
count++
})
console.log(count) // !30045015
console.timeEnd('enumerateCombinations') // !170ms
}