-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcombination.ts
70 lines (55 loc) · 1.46 KB
/
combination.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
export interface Box {
index: number;
list: any[];
}
export function combine(src: any[][]) {
const wrapped: Box[] = src.map(list => ({
index: 0,
list,
}));
const stack: Box[] = [];
const result: any[][] = [];
const doneMark = Array(src.length).fill(false);
while (true) {
const subResult: any[] = stack.reduce((acc, cur) => {
acc.push(cur.list[cur.index]);
return acc;
}, []);
while (wrapped.length) {
const cache = wrapped.shift();
if (cache.index < cache.list.length) {
subResult.push(cache.list[cache.index]);
} else {
;
}
stack.push(cache);
}
result.push(subResult);
while (stack.length) {
const cache = stack.pop();
if (cache.index + 1 < cache.list.length) {
cache.index++;
wrapped.unshift(cache);
break;
} else {
cache.index = 0;
wrapped.unshift(cache);
doneMark[stack.length] = true;
}
}
const done = doneMark.reduce((acc, cur) => acc & cur, true);
if (done) {
break;
}
}
return result;
}
if (require.main === module) {
const test = [
[ 1, 2, ],
[ 3, 4, ],
[ 5, 6, 7, ],
];
const r = combine(test);
console.log(r);
}