PowerShell for Windows Admins

Nov 25 2018   8:33AM GMT

Find pairs that give required sum

Richard Siddaway Richard Siddaway Profile: Richard Siddaway


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 {
param (


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

 Comment on this Post

There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: