Add++, the Language of the Month, has the "collect" builtin as BC
. Your task is to implement this builtin.
Consider a non-empty array, where each element is either:
- A positive digit between
1
and9
inclusive, or - A non-empty list of positive digits between
1
and9
For example, all the following such arrays meet this definition:
[1, 2, 3, 4, 5]
[7, [5, 3], 2]
[1, [2, 2], 3, [4, 4], 5]
[[1], 2, 3, [4], 5, [4], 2]
[[9, 4, 2]]
[[1], 2, 3, 4, 5, [6], 7]
[6, [1, 9, 4]]
Note that elements can be repeated, both the digits, the inner lists and the elements of the inner lists.
The BC
builtin "collects" adjacent digits in the array, and groups them into a list, while leaving the existing lists untouched. Applying this to the above lists, the examples make this clear:
[[1, 2, 3, 4, 5]]
[[7], [5, 3], [2]]
[[1], [2, 2], [3], [4, 4], [5]]
[[1], [2, 3], [4], [5], [4], [2]]
[[9, 4, 2]]
[[1], [2, 3, 4, 5], [6], [7]]
[[6], [1, 9, 4]]
For example, with [[1], 2, 3, 8, 9, [6], 7]
, we group the 2, 3, 8, 9
together, and the 7
to give [[1], [2, 3, 8, 9], [6], [7]]
You should take a ragged list as input, that meets the list format described above, and output a list of lists after the BC
builtin has been applied to the input. This is code-golf, so the shortest code in bytes wins.
Test cases
[[9, 4, 2]] -> [[9, 4, 2]]
[6, [1, 9, 4]] -> [[6], [1, 9, 4]]
[7, [5, 3], 2] -> [[7], [5, 3], [2]]
[1, 2, 3, 4, 5] -> [[1, 2, 3, 4, 5]]
[1, [2, 2], 3, [4, 4], 5] -> [[1], [2, 2], [3], [4, 4], [5]]
[[1], 2, 3, 8, 9, [6], 7] -> [[1], [2, 3, 8, 9], [6], [7]]
[[1], 2, 3, [4], 5, [4], 2] -> [[1], [2, 3], [4], [5], [4], [2]]
[9, 8, 7, 6, [5, 4, 3], 2, 1] -> [[9, 8, 7, 6], [5, 4, 3], [2, 1]]
[[8, 2], 9, 5, 1, [6, 4], [4, 5]] -> [[8, 2], [9, 5, 1], [6, 4], [4, 5]]
[7, [5, 3], 2, [1, 2, 3], 9, 8, 7, 8, 9, [3, 4], [1], [2]] -> [[7], [5, 3], [2], [1, 2, 3], [9, 8, 7, 8, 9], [3, 4], [1], [2]]
[[3,4,5]]
the same of[[3, 4, 5]]
? Also, how is the input formatted exactly, are spaces always there? \$\endgroup\$