-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenSubArr.js
83 lines (64 loc) · 1.92 KB
/
GenSubArr.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
'use strict';
let tests = [[], [0], [1,2], [1,2,3,4], [2,2,2,2]]; // basic tests
// generate large subarray test case
// let largeTestCase = [];
// for(let i = 1; i <= 1000; i++) {
// largeTestCase.push(i)
// }
// tests.push(largeTestCase);
for(let i = 0; i < tests.length; i++) {
// console.log("Test #" + (i+1) + ": subArr(" + tests[i] + ") == " + printSubArr(subArr(tests[i])));
// console.log("Test #" + (i+1) + ": subArr(" + tests[i] + ") == " + subArr(tests[i]));
let res = [];
subArr2(tests[i], 0, 0, res);
console.log("Test #" + (i+1) + ": subArr(" + tests[i] + ") == " + printSubArr(res));
}
// recursive version of subarray generation function
function subArr2(arr, start, end, res) {
if(end >= arr.length) {
return
} else if(start > end) {
subArr2(arr, 0, (end+1), res);
} else {
let thisSubArr = [];
for(let i = start; i < end; i++) {
thisSubArr.push(arr[i]);
}
thisSubArr.push(arr[end]);
res.push(thisSubArr);
subArr2(arr, (start+1), end, res)
}
}
// subArr() generates all sub-arrays of arr
// start with an outer loop of subarray lengths (starting 1). In the inner loop, set a sub array start index and increment
// by 1 until end of subarray is at the end of arr.
function subArr(arr) {
let result = [];
for(let subArrLen = 1; subArrLen <= arr.length; subArrLen++) {
for(let subArrStart = 0; subArrStart+subArrLen <= arr.length; subArrStart++) {
result.push(arr.slice(subArrStart, subArrStart+subArrLen));
}
}
return result;
}
// pretty printer for nested arrays
function printSubArr(arr) {
let result = "[";
for(let i = 0; i < arr.length; i++) {
if(i > 0) {
result += ", [";
} else {
result += "[";
}
for(let j = 0; j < arr[i].length; j++) {
if(j > 0) {
result += ", " + arr[i][j];
} else {
result += arr[i][j];
}
}
result += "]";
}
result += "]";
return result;
}