PowerShell for Windows Admins

Nov 26 2018   9:11AM GMT

A more elegant way to find pairs

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tags:
Powershell

Last time I showed a brute force way to find the pairs of numbers in an array that would sum to a given value. This time I have a more elegant way to find pairs.

 

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

[int]$value
)

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

foreach ($n in $iarray){
$target = $value – $n

if ($target -in $iarray) {
Write-Information -MessageData “Pair to give sum: ($n, $target)” -InformationAction Continue
}
}
}

 

Iterate through the array and for each element subtract the element from the required value. Test to see if this result is a member of the array and print out the pair if it is.

 

This has the advantage of printing the pair each way so for an example array

Array: 1 8 3 -3 6 4 9 5 10 2

 

You’ll get

Pair to give sum: (1, 6)

and

Pair to give sum: (6, 1)

 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: