## Find pairs that give required sum

If you have an array of integers how do you find pairs that give required sum. In other words which pairs of numbers add up to a given value.

There are a number of ways to solve this. Lets start with my favourite technique – brute force.

function get-pairs {
[CmdletBinding()]
param (
[int[]]\$iarray,

[int]\$value
)

Write-Information -MessageData “Array: \$iarray” -InformationAction Continue
Write-Information -MessageData “Sum: \$value” -InformationAction Continue

for (\$i=0; \$i -le (\$iarray.Count -1); \$i++){

for (\$j= \$i+1; \$j -le (\$iarray.Count -1); \$j++){

if( (\$iarray[\$i] + \$iarray[\$j]) -eq \$value) {

Write-Information -MessageData “Pair to give sum: (\$(\$iarray[\$i]), \$(\$iarray[\$j]))” -InformationAction Continue

}
}
}
}

Start by outputting the array and the required value for reference. Iterate through the array then for each value compare that with the values ahead of it in the array. You don’t need to compare earlier values because they’ve already been done – counter intuitive but correct as if you have a 1 and a 6 in the array you only count them once not as 1 and 6 and 6 and 1.

PS> \$iarray = 1,8,3,-3,6,4,9,5,10,2

PS> get-pairs -iarray \$iarray -value 7
Array: 1 8 3 -3 6 4 9 5 10 2
Sum: 7
Pair to give sum: (1, 6)
Pair to give sum: (3, 4)
Pair to give sum: (-3, 10)
Pair to give sum: (5, 2)

There are more elegant and quicker solutions that I’ll cover in subsequent posts

This entry was posted in Powershell. Bookmark the permalink.