-
Notifications
You must be signed in to change notification settings - Fork 0
/
lof_compensate.js
49 lines (43 loc) · 1.91 KB
/
lof_compensate.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
function LofCompensate(nestedArray) {
// Helper function to generate a random integer between min and max (inclusive)
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Helper function to insert a new [[]] structure at a random position within the array
function insertDoubleBracketAtRandomPosition(arr) {
let newElement = [[]];
let position = getRandomInt(0, arr.length);
if (arr.length === 0) {
arr.push(newElement);
} else {
arr.splice(position, 0, newElement);
}
}
// Helper function to recursively traverse the array and insert the new structure
function addAtRandomLocation(arr) {
if (arr.length === 0) {
insertDoubleBracketAtRandomPosition(arr);
} else {
let randomIndex = getRandomInt(0, arr.length);
if (Math.random() < 0.5 || !Array.isArray(arr[randomIndex])) {
insertDoubleBracketAtRandomPosition(arr);
} else {
addAtRandomLocation(arr[randomIndex]);
}
}
}
// Clone the original array to avoid modifying the input array directly
let clonedArray = JSON.parse(JSON.stringify(nestedArray));
addAtRandomLocation(clonedArray);
return clonedArray;
}
{
// Test cases
let testCase1 = [];
let testCase2 = [[],[],[[[[]]],[[[]]]]];
let testCase3 = [[],[],[[[[]]],[[[]]]]];
console.log(JSON.stringify(LofCompensate(testCase1))); // Output: [[[]]]
console.log(JSON.stringify(LofCompensate(testCase2))); // Possible outputs: [[[[]]],[],[[[[]]],[[[]]]]], [[],[[[],[[[[]]],[[[]]]]]]], etc.
console.log(JSON.stringify(LofCompensate(testCase3))); // Possible outputs: [[[[]]],[],[[[[]]],[[[]]]]], [[],[[[],[[[[]]],[[[]]]]]]], etc.
console.log(JSON.stringify(LofCompensate(testCase3))); // Possible outputs: [[[[]]],[],[[[[]]],[[[]]]]], [[],[[[],[[[[]]],[[[]]]]]]], etc.
}