Given a list of positive digits, return that list with consecutive elements grouped together. For example:
[1, 2, 3, 5, 6, 5, 4, 4, 1] -> [[1, 2, 3], [5, 6, 5, 4], [4], [1]]
Essentially, all adjacent elements whose absolute difference is 1 should be grouped together.
The input array will only ever contain positive digits (123456789
) and it's length will always fit within your language's integer limit. You may take input in any reasonable format, including as a string or a single integer (so the example would be \$123565441\$). The input will never be empty and will always contain at least 1 element
You may output in any reasonable format that clearly shows the separate groups. There must be clear, non-digit delimiters between the groups. There doesn't have to be clear delimiters between the elements of the groups. If there are, the delimiters between groups and the elements of groups should be distinct (basically, you can't just print the input saying that both are separated by ,
or whatever).
One example output is shown above. Another could be outputting each group on a separate line, as single strings of digits such as
123
5654
4
1
The input is not guaranteed to be sorted. The order of the outputs, or the elements in the outputs, does not have to match the order of the inputs, so long as the groups and elements are correct.
This is code-golf so the shortest code in bytes wins.
Test cases
[1] -> [1]
[1, 2] -> [[1, 2]]
[1, 3] -> [[1], [3]]
[2, 1] -> [[2, 1]]
[2, 4, 1, 2, 7, 6, 5, 1] -> [[2], [4], [1, 2], [7, 6, 5], [1]]
[4, 1, 8, 1, 3, 5, 3, 7, 1] -> [[4], [1], [8], [1], [3], [5], [3], [7], [1]]
[1, 2, 3, 4, 5, 6, 7, 9, 8] -> [[1, 2, 3, 4, 5, 6, 7], [9, 8]]
[1, 2, 3, 5, 6, 5, 4, 4, 1] -> [[1, 2, 3], [5, 6, 5, 4], [4], [1]]
[6, 1, 4, 4, 1, 2, 1, 4, 3, 2, 9, 2, 7, 5, 7, 3, 1, 7, 6, 5] -> [[6], [1], [4], [4], [1, 2, 1], [4, 3, 2], [9], [2], [7], [5], [7], [3], [1], [7, 6, 5]]
[6, 1, 4, 4, 1, 2, 3, 4, 3, 2, 9, 2, 7, 5, 7, 3, 1, 7, 6, 5] -> [[6], [1], [4], [4], [1, 2, 3, 4, 3, 2], [9], [2], [7], [5], [7], [3], [1], [7, 6, 5]]
0
as delimiters are disallowed? \$\endgroup\$0
will never be in the input, you can use it as a delimiter \$\endgroup\$