The objective of this challenge is to take an array of positive integers, and enumerate its indices, grouping like elements.
An enumeration without any duplicates is done by just outputting an array of pairs (value, index)
, for example, [3, 4, 13, 9, 2]
=> [[3,1],[4,2],[13,3],[9,4],[2,5]]
.
However, if a given element appears a second time, it isn't given its own pair, but is instead added to the group of its first occurrence. If in our above example we replaced the 9 with 3, then in the output we would remove [9,4]
and replace [3,1]
with [3,1,4]
.
In the output, groups must be ordered by their first occurrence, and indices must be in ascending order. The element must be first in a group, before its indices. Output may be 0 or 1 indexed. You may assume the array has at least one element.
Test cases:
Input | Output (One-indexed)
[3, 2, 2, 3] | [[3, 1, 4], [2, 2, 3]]
[17] | [[17, 1]]
[1, 1] | [[1, 1, 2]]
[1, 1, 2] | [[1, 1, 2], [2, 3]]
[1, 2, 3, 4] | [[1, 1], [2, 2], [3, 3], [4, 4]]
[1, 1, 1, 1] | [[1, 1, 2, 3, 4]]
This is code-golf, fewest bytes wins!
[[17,"1"]]
? (Don't know yet if I can save any bytes that way, still working on it!) \$\endgroup\$[[3, [1, 4]], [2, [2, 3]]]
instead? \$\endgroup\$