Monthly Archive

Categories

A more elegant way to find pairs

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)

Comments are closed.