Skip to main content
1 of 6

Collect the elements of an array

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 and 9 inclusive, or
  • A non-empty list of positive digits between 1 and 9

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" consecutive 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, 4, 5, [6], 7], we group the 2, 3, 4, 5 together, and the 7 to give [[1], [2, 3, 4, 5], [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 , 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, 4, 5, [6], 7] -> [[1], [2, 3, 4, 5], [6], [7]]
[[1], 2, 3, [4], 5, [4], 2] -> [[1], [2, 3], [4], [5], [4], [2]]