Scripting Games, Advanced Event 7, Play Ball

Work out a rota for games between 6 teams; randomise the list to avoid one team playing too many consecutive games.

  1 $games=@()
  2 $teams=‘A’,‘B’,‘C’,‘D’,‘E’,‘F’
  4 for ($i=0; $i -lt $teams.length; $i++) {
  5     $iTeam=$teams[$i]
  6     for ($j=$i+1; $j -lt $teams.length; $j++) {
  7         $jTeam=$teams[$j]
  8         # Following line distributes home and away games :-)
  9         if (($i+$j)%2) {$games+="$iTeam vs. $jTeam"} else {$games+="$jTeam vs. $iTeam"}
10     }
11 }
13 # Mix the games up by repeatedly swapping array elements with other random elements
14 $element= New-Object System.Random
16 for ($i=$games.length-1; $i -ge 0; $i–) {
17     $index=$,$i)
18     # Swapping element $i with $index…
19     $x=$games[$i]; $games[$i]=$games[$index]; $games[$index]=$x
20 }
22 $games

So, the script is in two sections: the first part (lines 4-11) works out the list of possible unique games between the teams (and saves them in $games).  By taking even- and odd-numbered fixtures (line 9) we distribute home and away games (not required, but seemed fair:-)

Lines 14-20 use an algorithm known as a Fisher-Yates shuffle to mix up the games in a random way by swapping (in place) elements of the array with random other elements.  Item one is swapped with an item randomly selected between 1..n.  Item 1 is, in effect, now an element randomly selected from the whole array.  Item 1 is now left alone and item 2 is randomly selected from the remaining items (2..n).  And so on…  (Note: in this script, for some reason, I started at the last element and worked backwards – not sure why but normality is returned the next time this algorithm appears!)

The resulting fixtures are displayed (line 20) and that’s it.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s