25
\$\begingroup\$

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 , fewest bytes wins!

\$\endgroup\$
9
  • \$\begingroup\$ 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!) \$\endgroup\$
    – Shaggy
    Jan 19, 2018 at 18:52
  • \$\begingroup\$ @shaggy sure, that's fine \$\endgroup\$
    – Pavel
    Jan 19, 2018 at 19:02
  • 3
    \$\begingroup\$ Possible duplicate. \$\endgroup\$ Jan 19, 2018 at 21:13
  • 1
    \$\begingroup\$ Can we output something like [[3, [1, 4]], [2, [2, 3]]] instead? \$\endgroup\$ Jan 20, 2018 at 1:09
  • 1
    \$\begingroup\$ @Pavel that's no reason :p but sure \$\endgroup\$ Jan 20, 2018 at 1:34

31 Answers 31

1
2
0
\$\begingroup\$

Arturo, 57 bytes

$[a][map unique a'x[@[x]++select 1..size a'y->x=a\[y-1]]]

Try it

$[a][                           ; a function taking an argument a
    map unique a 'x [           ; map over unique numbers in a and assign current number to x
        @[x]                    ; x as a list
        ++                      ; prepended to
        select 1..size a 'y ->  ; the indices in a where...
            x = a\[y-1]         ; x equals the value in a at the current index
    ]                           ; end map
]                               ; end function
\$\endgroup\$
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.