0

I have the following problem,

I want to get the pair of given sum by using higher order functions. I am able to do this using iterative approach. Can someone help me to solve the problem using Swift higher order functions like map, filter etc.

    let array = [1,2,3,4,5]
    let givenSum = 9
    for i in 0..<array.count {
      let j = i + 1
        for j in j..<array.count {
          if array[i] + array[j] == givenSum {
          print("Pair : \(array[i]),\(array[j])")
      }
   }
 }

The output is [4,5]

Any help is appreciated. Thank you

Ajay K
  • 3
  • 1

2 Answers2

0

@Ajay K I think we need to use for loop in any way to implement this solution Still, you can use the following improved solution

var map = [Int: Int]()
for (i, n) in array.enumerated() {
    let diff = givenSum - n
    if let j = map[diff] {
        print("Pair : \(array[i]),\(array[j])")
    }
    map[n] = i
}

Happy Coding. Open for thoughts!

teja_D
  • 383
  • 3
  • 18
0
let array = [1,5,2,3,4]
let givenSum = 9

let resultArray = array.sorted().filter{ array.firstIndex(of: givenSum-$0) ?? -1 > array.firstIndex(of: $0)!}.map{ ($0 , givenSum - $0)}

print((resultArray))

The above code gives you the expected result with higher order functions (I did not check it for lots of cases).

udi
  • 3,672
  • 2
  • 12
  • 33