@alexandermomchilov/

# Enumerate an array, grouping duplicates

## https://codegolf.stackexchange.com/questions/153604/enumerate-an-array-grouping-duplicates

Files
• main.swift
main.swift
```1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
```
```let golfed: ([Int]) -> [[Int]] = {a in Dictionary(grouping:a.enumerated()){\$0.1}.sorted{\$0.1.first!.0<\$1.1.first!.0}.map{[\$0]+\$1.map{\$0.0}}}

let ungolfed = { (input: [Int]) -> [[Int]] in
return Dictionary(grouping: input.enumerated(), by: { \$0.element })
.sorted { pairA, pairB in // Sort by order of first appearence (lowest offset)
return pairA.value.first!.offset < pairB.value.first!.offset
}.map { element, pairs in
return [element] + pairs.map{ \$0.offset + 1 } //+1 here converts to 1-based indexing
}
}

let testcases: [(input: [Int], expected: [[Int]])] = [
(input: [3, 2, 2, 3], expected: [[3, 1, 4], [2, 2, 3]]),
(input: [17], expected: [[17, 1]]),
(input: [1, 1], expected: [[1, 1, 2]]),
(input: [1, 1, 2], expected: [[1, 1, 2], [2, 3]]),
(input: [1, 2, 3, 4], expected: [[1, 1], [2, 2], [3, 3], [4, 4]]),
(input: [1, 1, 1, 1], expected: [[1, 1, 2, 3, 4]]),
]

let f = ungolfed

for (input, expected) in testcases {
let result = f(input)
print("\(input) \t\t\t|\t\t\t\(result)")
}```