36
2
Note: This is #2 in a series of array-manipulation challenges. For the previous challenge, click here.
Separating Nested Lists
To separate values in a nested list, flatten it, and then wrap each value so it is at the same nested depth as before.
That is to say, this list:
[1, [2, 3], [4, 4, [5, 2], 1]]
Would become:
[1, [2], [3], [4], [4], [[5]], [[2]], [1]]
The Challenge
Your task is to write a program which takes any nested list of positive integers (within your language's limits) and performs this separation operation.
You may submit a function which takes the list as an argument, or a full program which performs I/O.
As this is code-golf, the shortest submission (in bytes) wins!*
*Standard golfing loopholes are banned. You know the drill.
Test Cases
Input lists will only ever contain integers in your language's standard integer size. To avoid languages' constraints preventing them from competing, values will not be nested at depths of more than 10.
You may assume that input will not have empty sub-lists: for example - [[5, []]]
will not be given. However, the main list could be empty.
[] -> []
[[1, 2]] -> [[1], [2]]
[3, [4, 5]] -> [3, [4], [5]]
[3, [3, [3]]] -> [3, [3], [[3]]]
[[6, [[7]]]] -> [[6], [[[7]]]]
[[5, 10], 11] -> [[5], [10], 11]
Don't hesitate to leave a comment if I've missed out a corner case.
Example
I threw together a quick (ungolfed) Python 3 solution as an example - you can test it on repl.it.
Add a testcase with bigger than single digit numbers for string based answers. – orlp – 2016-12-20T22:44:42.937
@orlp good idea. – FlipTack – 2016-12-20T22:45:38.930
2Can we assume a certain maximum depth? Say, 16? – orlp – 2016-12-20T22:51:09.580
@orlp I'm going to say yes, the maximum nested depth will be 10, as I'm more interested in your algorithm and method execution than your language's constraints. Will update thread now. – FlipTack – 2016-12-20T23:11:37.163
May I output as a string? – Rohan Jhunjhunwala – 2016-12-20T23:17:20.053
@RohanJhunjhunwala as always with code-golf, I/O is flexible. As long as the string is a valid, unambiguous representation of a list, then that is fine. – FlipTack – 2016-12-20T23:39:41.007
The input list will not contain
0
, right? – Zacharý – 2016-12-24T00:15:14.473@ZacharyT yep, only positive integers (0 isn't regarded as positive on PPCG: if I wanted to include 0, I would say "non-negative") – FlipTack – 2016-12-24T00:29:25.283