24
4
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!
Would it be acceptable for the indides to be output as strings, e.g.
[[17,"1"]]
? (Don't know yet if I can save any bytes that way, still working on it!) – Shaggy – 2018-01-19T18:52:42.517@shaggy sure, that's fine – Pavel – 2018-01-19T19:02:45.923
may we output to stdout using a consistent separator? For example,
1 1 2\n2 3
for the fourth test case? – Giuseppe – 2018-01-19T19:07:53.270although I suppose that then you couldn't see the two-dimensional structure of the last test case at it would be
1 1 2 3 4
– Giuseppe – 2018-01-19T19:12:19.933@Giuseppe No, that's fine. In all cases there would be a kind of 'implicit'
[]
wrapped around the output. – Pavel – 2018-01-19T20:04:33.1633Possible duplicate. – totallyhuman – 2018-01-19T21:13:31.540
1Can we output something like
[[3, [1, 4]], [2, [2, 3]]]
instead? – Conor O'Brien – 2018-01-20T01:09:53.213@ConorO'Brien Sorry, no. I can't allow that because it will make existing answers be non-optimal. – Pavel – 2018-01-20T01:34:15.760
1@Pavel that's no reason :p but sure – Conor O'Brien – 2018-01-20T01:34:58.240