Consider the array [5, 6, 8, 3, 9, 4, 2, 1, 7]
. If we list how far each number has moved from it's (1-indexed*) index, we have (considering absolute distance):
Array: [5, 6, 8, 3, 9, 4, 2, 1, 7]
Index: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Dists: 4 4 5 1 4 2 5 7 2
We can then group the elements of the array based on their distance away from their indices:
[[3], [4, 7], [5, 6, 9], [8, 2], [1]]
Additionally, we can optionally include empty lists to indicate distances not there (e.g. 0
):
[[], [3], [4, 7], [], [5, 6, 9], [8, 2], [], [1], []]
Note that the maximum distance an element can be from its index is len(list) - 1
and the minimum is 0
, so the list (including empty lists) will always be the same length or less as the original list.
*: Note that it doesn't matter if we use 1 or 0 indexing
Given a list of n
positive integers, group the elements of the list by their absolute distance from their indices. The input is guaranteed to be a permutation of [1, 2, 3, ..., n]
and will have a minimum of 3
elements. You may choose to include empty lists in the output, but only if the length of the output is the same length as the input.
The elements of the groups can be separated with any clear, consistent, non-digit separator, and the groups themselves should be separated in the same way, but with a separator that's different from that used to separate the elements of the groups. For example, spaces and newlines, or nested lists.
This is code-golf so the shortest code in bytes wins.
Test cases
[1, 3, 2] -> [[1], [3, 2]]
[3, 2, 4, 1] -> [[2], [4], [3], [1]]
[1, 2, 3, 4] -> [[1, 2, 3, 4]]
[2, 5, 3, 1, 4, 6] -> [[3, 6], [2, 4], [5, 1]]
[2, 1, 3, 6, 5, 7, 4] -> [[3, 5], [2, 1, 7], [6], [4]]
[1, 7, 4, 2, 8, 6, 3, 5] -> [[1, 6], [4], [2], [8, 5], [3], [7]]
[2, 6, 8, 3, 1, 7, 9, 5, 4] -> [[2, 3, 7], [9], [5], [6, 1], [8, 4]]
[5, 6, 8, 3, 9, 4, 2, 1, 7] -> [[3], [4, 7], [5, 6, 9], [8, 2], [1]]
[1, 7, 5, 10, 8, 9, 6, 3, 4, 2] -> [[1], [6], [5], [8, 9], [7, 3, 4], [10], [2]]
[10, 8, 5, 9, 2, 3, 4, 7, 6, 1, 11, 12] -> [[11, 12], [7], [5], [2, 3, 4, 6], [9], [8], [10, 1]]
[3, 5, 10, 11, 6, 7, 12, 14, 8, 2, 9, 13, 1, 4] -> [[6, 7, 8, 13], [3, 9], [5], [12], [14], [10, 11], [2], [4], [1]]
[6, 14, 8, 9, 12, 4, 13, 7, 5, 15, 10, 11, 3, 1, 2] -> [[7, 10, 11], [4], [5], [6, 8, 9, 15], [13], [12], [3], [14], [1, 2]]
[8, 12, 13, 7, 16, 5, 14, 15, 3, 10, 2, 4, 1, 9, 11, 6] -> [[10], [5], [7], [11], [9], [3], [8, 14, 15], [4], [2], [12, 13, 6], [16], [1]]
[14, 5, 10, 1, 2, 4, 13, 9, 7, 12, 8, 11, 3, 15, 16, 6] -> [[9, 11, 15, 16], [4, 7, 12], [5, 1, 2, 8], [13], [10], [3, 6], [14]]
[19, 8, 16, 15, 2, 6, 11, 18, 12, 9, 3, 14, 4, 1, 7, 5, 17, 13, 10] -> [[6, 17], [9], [14], [2, 12], [11], [13], [8], [3, 7], [4, 10], [18], [15, 5], [16, 1], [19]]
[19, 11, 7, 5, 3, 1, 20, 16, 17, 15, 10, 13, 6, 18, 2, 12, 9, 4, 14, 8] -> [[5, 10, 13], [3], [7, 18, 12], [1, 15, 14], [6], [16, 17, 9], [11], [8], [20, 2], [4], [19]]
0 ... n-1
) if you like \$\endgroup\$