Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(fix)[flatten-array]: Enable Flattening of all nested arrays in the array #577

Open
wants to merge 4 commits into
base: master
Choose a base branch
from

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