-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflatten_array.js
59 lines (48 loc) · 1013 Bytes
/
flatten_array.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
57
58
59
"use strict";
/*
* flatten array using Depth-first Search
* assuming elements in arr are either number or array
*/
function dfsFlatten(arr) {
const res = [];
dfs(arr, res);
return res;
}
// helper function for dfsFlatten
function dfs(item, res) {
if (typeof item === "number") {
res.push(item);
return ;
}
for (let i = 0; i < item.length; ++i) {
dfs(item[i], res);
}
}
/*
* flatten array using Breath-first Search
* assuming elements in arr are either number or array
*/
function bfsFlatten(arr) {
const res = [];
const queue = arr;
let item;
while (queue.length) {
item = queue.shift();
if (typeof item === "number") {
res.push(item);
} else {
queue.push(...item);
}
}
return res;
}
const raw_input = [
1,
2,
[3,4, [5,6,0]],
4,
[3,7],
0
];
console.log("DFS:", dfsFlatten(raw_input)); // DFS: [ 1, 2, 3, 4, 5, 6, 0, 4, 3, 7, 0 ]
console.log("BFS:", bfsFlatten(raw_input)); // BFS: [ 1, 2, 4, 0, 3, 4, 3, 7, 5, 6, 0 ]