PowerShell for Windows Admins

Nov 27 2018   6:44AM GMT

Third way to find pairs for given sum

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tags:
Powershell

There’s a third way to find pairs for given sum that’s a bit more complicated.

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

[int]$value
)

$sarray = $iarray | Sort-Object

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

$left = 0
$right = $sarray.Count – 1

while ($left -lt $right){
Write-Verbose -Message “left = $left  right =$right”
$sum = $sarray[$left] + $sarray[$right]

if ($sum -eq $value){
Write-Information -MessageData “Pair to give sum: ($($sarray[$left]), $($sarray[$right]))” -InformationAction Continue
$left += 1
$right -= 1
}
elseif ($sum -lt $value) {
$left += 1
}
elseif ($sum -gt $value){
$right -= 1
}
}
}

 

In this technique start by sorting the array. I’ve sorted it ascending which is the default.

 

Set the initial counters to the start and end of the sorted array. Use the while loop to work through the array. Sum the array elements and test if the sum equals the required value – if it does print the results and increment the left counter and decrement the low counter (move them closer together).

 

If the sum is less than the required value increment the left counter and if its more decrement the right counter.

 

Eventually the counters will meet, the right counter will be greater than the left counter and the loop will finish.

 

This technique takes a bit of thinking about so this is a run with the counter values printed

PS> get-pairs2 -iarray $iarray -value 7 -Verbose
Array: 1 8 3 -3 6 4 9 5 10 2
Sorted Array: -3 1 2 3 4 5 6 8 9 10
Sum: 7
VERBOSE: left = 0  right =9
Pair to give sum: (-3, 10)
VERBOSE: left = 1  right =8
VERBOSE: left = 1  right =7
VERBOSE: left = 1  right =6
Pair to give sum: (1, 6)
VERBOSE: left = 2  right =5
Pair to give sum: (2, 5)
VERBOSE: left = 3  right =4
Pair to give sum: (3, 4)

 

Next time we’ll start to  look at some string handling techniques

 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: