If you aren't already in the know, these ten problems are from the 2008 Winter Scripting games.

For each problem, I'm going to quickly sum up the interesting (interesting TO ME) bits of each problem, then I'm going to post the full source.

Event 7: Play Ball!

Here we are asked to randomly schedule games for six teams in a round robin tournament. Apparently I used Knuth's classic list order randomization algorithm, which I remember attempting to implement, badly, and failing!,  in high school. Yay for progress.

Otherwise the solution is straightforward: two nested loops, generate matches in a "combinatorial" way, then randomize the order. Boom, done.


$teams = @("A", "B", "C", "D", "E", "F")

#bad random number generator
$rnd = new-object Random

function Create-GameObject ($game)
    $o = new-object PSObject
    Add-Member -inputObject $o -memberType NoteProperty -name "Game" -value $game
    Add-Member -inputObject $o -memberType NoteProperty -name "RandomOrder" -value $rnd.NextDouble()   

function Generate-RoundRobinGames
    for ($firstTeamIndex = 0; $firstTeamIndex -lt $teams.Count; $firstTeamIndex++)
        for ($secondTeamIndex = $firstTeamIndex + 1; $secondTeamIndex -lt $teams.Count; $secondTeamIndex++)
            #POSTSCRIPT-OOPS - nitpick mostly. Reading MOW's solution has enlightened me
            #that, instead of creating objects and bolting properties onto them one at a time
            #as I do in the function referenced below, I could achieve the same result with
            #some well-constructed
            #    Select-Object @{Name=""; Expression={"stuff goes here"} }
            Create-GameObject -game "$($teams[$firstTeamIndex]) vs. $($teams[$secondTeamIndex])"

function Solve-Problem7
    $unsortedGames = Generate-RoundRobinGames

    Write-Host ($unsortedGames | sort RandomOrder | % { $_.Game } | out-string)


2008 Winter Scripting Game Events: Index