-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlof_cancel.js
61 lines (51 loc) · 1.94 KB
/
lof_cancel.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
function LoFCancel(nestedArray) {
console.log("WTF");
// Helper function to flatten and find all bracket pairs
function findBracketPairs(arr, parentIndex = []) {
let pairs = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
let currentIndex = parentIndex.concat(i);
if (arr[i].length === 1 && Array.isArray(arr[i][0]) && arr[i][0].length === 0) {
pairs.push(currentIndex);
}
pairs = pairs.concat(findBracketPairs(arr[i], currentIndex));
}
}
return pairs;
}
// Helper function to remove the selected pair of brackets
function removeAtPath(arr, path) {
if (path.length === 1) {
arr.splice(path[0], 1);
} else {
removeAtPath(arr[path[0]], path.slice(1));
}
}
// Find all bracket pairs
let bracketPairs = findBracketPairs(nestedArray);
if (bracketPairs.length === 0) {
return nestedArray;
}
// Select a random pair to remove
let randomPair = bracketPairs[Math.floor(Math.random() * bracketPairs.length)];
// Remove the selected pair of brackets
removeAtPath(nestedArray, randomPair);
return nestedArray;
}
// Test cases
{
let testCase1 = [[[]]];
let testCase2 = [[[]], [[]]];
let testCase3 = [[[], []], []];
let testCase4 = [[], [[]]];
let testCase5 = [[[[[]]]]];
let testCase6 = [[[[[]]]],[[[[], [[[[]]]]]]]];
console.log(JSON.stringify(LoFCancel(testCase1))); // Output: []
console.log(JSON.stringify(LoFCancel(testCase2))); // Output: [[[]]]
console.log(JSON.stringify(LoFCancel(testCase3))); // Output: [[[]], []]
console.log(JSON.stringify(LoFCancel(testCase4))); // Output: [[]]
console.log(JSON.stringify(LoFCancel(testCase5))); // Output: [[[[]]]]
console.log(JSON.stringify(LoFCancel(testCase6))); // Output: [[[[]]]]
console.log(JSON.stringify(LoFCancel(testCase6))); // Output: [[[[]]]]
}