-
Notifications
You must be signed in to change notification settings - Fork 30
/
combinations.ts
86 lines (76 loc) · 2.13 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
* 遍历所有大小为`r`的组合.
* @param arr 待遍历的数组.
* @param r 组合大小.
* @param cb 回调函数, 用于处理每个组合的结果.返回`true`时停止遍历.
* @param copy 是否浅拷贝每个组合的结果, 默认为`false`.
* @example
* ```ts
* enumerateCombinations([1, 2, 3, 4], 2, comb => {
* console.log(comb)
* })
* // [ 1, 2 ]
* // [ 1, 3 ]
* // [ 1, 4 ]
* // [ 2, 3 ]
* // [ 2, 4 ]
* // [ 3, 4 ]
* ```
* @complexity C(30,10)(3e7) => 347.592ms
*/
function enumerateCombinations<C>(arr: ArrayLike<C>, r: number, cb: (comb: readonly C[]) => boolean | void, copy = false): void {
bt(0, [])
function bt(pos: number, path: C[]): boolean {
if (path.length === r) {
return !!cb(copy ? path.slice() : path)
}
for (let i = pos; i < arr.length; i++) {
path.push(arr[i])
if (bt(i + 1, path)) return true // 不可取重复的元素
path.pop()
}
return false
}
}
/**
* 模拟python的`itertools.combinations`.
* @complexity C(24,10)(2e6) => 946.732ms
* @deprecated
*/
function* combinations<C>(arr: ArrayLike<C>, r: number): Generator<C[]> {
yield* bt(0, [])
function* bt(pos: number, path: C[]): Generator<C[]> {
if (path.length === r) {
yield path.slice()
return
}
for (let i = pos; i < arr.length; i++) {
path.push(arr[i])
yield* bt(i + 1, path) // 不可取重复的元素
path.pop()
}
}
}
export { enumerateCombinations }
if (require.main === module) {
enumerateCombinations([1, 2, 3, 4], 2, comb => {
console.log(comb)
})
const n = 30
const r = 10
const arr = Array.from({ length: n }, (_, i) => i)
console.time('enumerateCombinations')
let count = 0
enumerateCombinations(arr, r, () => {
count++
})
console.log(count) // !1961256
console.timeEnd('enumerateCombinations') // !34.127ms
// console.time('combinations')
// let count = 0
// for (const _ of combinations(arr, r)) {
// count++
// }
// console.timeEnd('combinations') // !910.397ms
// console.log(count) // !1961256
}