You will be given as input a non-empty list of positive integers. For example:
[1,2,2,2,1]
You want to produce a ragged list as output which has this as its "depth map". This list should have the same elements in the same order but each element n
should be at the depth equal to its value.
[1,[2,2,2],1]
This is a list where the 1
s are at the first level, the 2
s are nested in there, the threes would be nested in that etc.
There are multiple outputs that fit this description:
[1,[2],[2],[2],1]
[1,[],[2,[],2,2],1]
[1,[2,2,2],1,[[[]]]]
We want the simplest one, that is the one with the fewest lists total. So in this case
[1,[2,2,2],1]
only has 2 lists whereas all the other examples had more.
Task
Take a depth map and produce the simplest ragged list that it could represent as outlined above.
This is code-golf so the goal is to minimize the size of your source code as scored in bytes.
Test cases
[1] -> [1]
[2] -> [[2]]
[3] -> [[[3]]]
[10] -> [[[[[[[[[[10]]]]]]]]]]
[1,2] -> [1,[2]]
[2,2] -> [[2,2]]
[2,1,2] -> [[2],1,[2]]
[1,2,3,2] -> [1,[2,[3],2]]
[1,2,3,3,3,2,1] -> [1,[2,[3,3,3],2],1]
[1,2,1,2,1,3,3,1] -> [1,[2],1,[2],1,[[3,3]],1]