Wednesday, April 23, 2008 3:46:13 AM UTC #

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.

Source

#PROBLEM #7
$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()   
   
    $o
}


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"} }
            #statements.
            Create-GameObject -game "$($teams[$firstTeamIndex]) vs. $($teams[$secondTeamIndex])"
        }
    }
}


function Solve-Problem7
{
    $unsortedGames = Generate-RoundRobinGames


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


Solve-Problem7

2008 Winter Scripting Game Events: Index

Categories: PowerShell
Technorati:
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, b, blockquote@cite, em, i, strike, strong, sub, sup, u) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview
Syndication

Search
Posts on this page
Categories
Sites I visit regularly
About

Powered by: newtelligence dasBlog 2.1.8102.813

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2008, Peter Seale

Send mail to the author(s) E-mail



Sign In