header image

A more elegant way to find pairs

Posted by: | November 26, 2018 Comments Off on 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 {
param (


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)


Pair to give sum: (6, 1)

under: PowerShell

Comments are closed.