Higher Order Function

Hi there,

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 higher order function.

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

The output is [2,3]

Any help is appreciated. Thank you

I want to get the pair of given sum by using higher order functions.

What do you mean by higher order ? Do you mean using func as map, filter…

Is it the real code ? It does not compile.

Or is it

    if array[i] + array[j] == givenSum { // instead of givenNum {

Your code works but is confusing and error prone. Reusing j for the loop

  let j = i + 1
  for j in j..<array.count {

If you do this on more complex code, you may have hard to find bugs.

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

Oh Sorry! it was supposed to be givenSum instead of givenNum. Can you please how to solve the above problem using swift higher order functions like map, filter etc.

@DelawareMathGuy proposed a solution with map and filter. However in your case, your simple solution is quite OK.

Higher Order Function
 
 
Q