r/PowerShell • • Dec 08 '25

Saving Christmas with PowerShell: Building a Reusable Matching Algorithm

This video isn’t just “here’s a script.” It walks step-by-step through the whole evolution of the solution:

  • Start with a naive random shuffle
  • Add constraints and filtering
  • Introduce backtracking when things get messy
  • Turn it all into a clean, reusable function

The end result is a robust matching engine you can adapt for scheduling, load balancing, on-call rotations, pairing systems, etc.

Watch: https://youtu.be/4uwQh6Nap5M

Code: https://www.dowst.dev/?p=3971

Feedback and ideas welcome!

13 Upvotes

8 comments sorted by

View all comments

Show parent comment

1

u/Future-Remote-4630 Dec 18 '25

More control is more risk, though in many circumstances you have a good point in that there is value to having access to the variable that defines the looping.

I would evaluate each approach very differently in the context of using it to loop through integers, as seen in this example, versus using it to index into an array. In some circumstances, it is critical to touch every value, and with a for loop, having access to the variable that defines the looping logic means it's possible to make a mistake that stops you from touching every object, whereas with the foreach structure, that is not the case.

Depending on the sample size, you'll also encounter a difference in performance.

Consider these:

Function Test-LoopSpeeds(){
    $For = {
        $max = 10000000
        $l = for($i = 0; $i -le $max; $i++){
            $i 
        }
    }
    $For_Measure = measure-command -expression $For
    $Foreach = {
        $max = 10000000
        $l = Foreach($i in 0..$Max){
            $i
        }
    }
    $Foreach_Measure = measure-command -expression $Foreach
    $ForeachObj = {
        $l = 0..10000000 | Foreach-Object { $_ }
    } 
    $ForeachObj_Measure = measure-command -expression $ForeachObj
    $ForeachObjp = {
        $l = 0..10000000  | Foreach-Object -parallel { $_ }
    } 
    $ForeachObjp_Measure = measure-command -expression $ForeachObj
    "For_Measure:  $($For_Measure.TotalMilliseconds)"
    "Foreach_Measure:  $($Foreach_Measure.TotalMilliseconds)" 
    "ForeachObj_Measure:  $($ForeachObj_Measure.TotalMilliseconds)"
    "ForeachObjp_Measure:  $($ForeachObjp_Measure.TotalMilliseconds)"
}
Test-LoopSpeeds

# >> Test-LoopSpeeds
# >>
# For_Measure:  2957.7278
# Foreach_Measure:  1690.4738
# ForeachObj_Measure:  10832.6707
# ForeachObjp_Measure:  12041.38