hi,
if you're willing to use the combinations
function that's defined in the Algorithms package, this will work for you:
import Algorithms
print([1,2,3,4].combinations(ofCount: 2).filter({ $0[0] + $0[1] == 5 }))
in the code above, combinations(ofCount : 2) gives all pairs, and then pull out all those pairs which add to 5. the output, by the way, is:
[[1, 4], [2, 3]]
if you don't want to use the combinations function, and you don't like doing your own iteration, then you could replace it with perhaps a recursive function. one such possibility would be:
func allPairs(numbers: [Int]) -> [[Int]] {
guard numbers.count >= 2 else {
return []
}
let firstElement = numbers[0]
let remainingElements = numbers.dropFirst()
let pairsWithFirstElement = remainingElements.map({ [firstElement, $0] })
let pairsWithoutFirstElement = allPairs(numbers: Array(remainingElements))
return pairsWithFirstElement + pairsWithoutFirstElement
}
so this code gives the same result as above:
print(allPairs(numbers: [1,2,3,4]).filter({ $0[0] + $0[1] == 5 }))
hope that's useful for you,
DMG