DEV Community

Discussion on: Daily Challenge #215 - Difference of 2

Collapse
 
kesprit profile image
kesprit

My Swift solution :

func pairDifference(tab: [Int]) -> [[Int]]{
    tab.sorted().reduce(into: [[Int]]()) { (result, intValue) in
        if let value = tab.first(where: { $0 == intValue + 2 }) {
            result.append([intValue, value])
        }
    }
}

pairDifference(tab: [1, 2, 3, 4]) // [[1, 3], [2, 4]]
pairDifference(tab: [4, 1, 2, 3]) // [[1, 3], [2, 4]]
pairDifference(tab: [1, 23, 3, 4, 7]) // [[1, 3]]
pairDifference(tab: [4, 3, 1, 5, 6]) // [[1, 3], [3, 5], [4, 6]]