Skip to content

Conversation

superhit0
Copy link

@superhit0 superhit0 commented Feb 4, 2024

Fixes: #564

Algorithm:

- Loop over depth till depth becomes 0
 - if in any iteration the depth > 0 but array does not contain any array as its element, then break
 - Iterate over the current array and if the current element is not an array, simply push it to next stack otherwise unwrap the array of one depth and then push the unwrapped array into next stack array

Dry Run:

Input Sample 1:
Input Array = [[1, [2, 3], 4], [5, [6, [7, [8]]]]];
Depth = 6;
Result = [1, 2, 3, 4, 5, 6, 7, 8];

Depth Array At Start of Iteration Array At End of Iteration
6 [[1, [2, 3], 4], [5, [6, [7, [8]]]]] [1, [2, 3], 4, 5, [6, [7, [8]]]]
5 [1, [2, 3], 4, 5, [6, [7, [8]]]] [1, 2, 3, 4, 5, 6, [7, [8]]]
4 [1, 2, 3, 4, 5, 6, [7, [8]]] [1, 2, 3, 4, 5, 6, 7, [8]]
3 [1, 2, 3, 4, 5, 6, 7, [8]] [1, 2, 3, 4, 5, 6, 7, 8]
2 [1, 2, 3, 4, 5, 6, 7, 8] [1, 2, 3, 4, 5, 6, 7, 8]
1 [1, 2, 3, 4, 5, 6, 7, 8] (break Due to Array containing no array)

Input Sample 2:
Input Array = [[1, [2, 3], 4], [5, [6, [7, [8]]]]];
Depth = 3;
Result = [1, 2, 3, 4, 5, 6, 7, [8]];

Depth Array At Start of Iteration Array At End of Iteration
3 [[1, [2, 3], 4], [5, [6, [7, [8]]]]] [1, [2, 3], 4, 5, [6, [7, [8]]]]
2 [1, [2, 3], 4, 5, [6, [7, [8]]]] [1, 2, 3, 4, 5, 6, [7, [8]]]
1 [1, 2, 3, 4, 5, 6, [7, [8]]] [1, 2, 3, 4, 5, 6, 7, [8]]
0 [1, 2, 3, 4, 5, 6, 7, [8]] (break Due to depth === 0)

@superhit0
Copy link
Author

@angus-c please let me know your thoughts on this PR. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

flatten with depth=1 is not properly applied to the first element
1 participant