Scripting Games, Advanced Event 2, Skating on Thin Ice

I liked this one:-)

The idea was to add up a set of skaters’ scores (provided in a file) to arrive at the Gold, Silver and Bronze medal winners for the event.

Along with event 1, this really shows how PowerShell can make this kind of task easy.

The bulk of the script is in the first statement.  This reads in the skaters names and scores from the specified file, it then:

  • Creates a custom object to hold each skater’s name and calculated final score
  • Splits the result entry from the file into name and (seven) scores
  • Sorts the given seven individual scores and selects the centre 5 of these, thereby discarding the highest and lowest score
  • Calculates the average of these 5 scores and adds this value to the result object
  • Outputs the resulting object to the pipeline where it is sorted (descending) by total score

The output from the pipeline is stored in array $Results, the top three items are then read from this array and the skaters awarded the Gold, Silver and Bronze medals accordingly.

  1 $Results=$(foreach ($entry in get-content ‘c:\scripts\skaters.txt’) {
  2     $skater=[object]|select name, score
  3     $skater.name, $scores=$entry.split(‘,’)
  4     $skater.score=($scores|sort)[1..5]|%{$avg=0}{$avg+=$_}{$avg/5}
  5     $skater
  6 })|sort -descending score
  7
  8 $Medals="Gold", "Silver", "Bronze"
  9 0..2|%{"$($Medals[$_]) medal: $($Results[$_].name), $($Results[$_].score)"}

Advertisements

2 thoughts on “Scripting Games, Advanced Event 2, Skating on Thin Ice”

  1. Don\’t know why, but I had a real mental block in this event – not in finding the medalists, but working out how to display them! Next time I\’m writing PowerShell for an ice skating competition I\’m using your lines 8 and 9 ;-)

  2. I originally had three lines with hardcoded "Gold medal" etc, but worked out I could do it in 2 lines :-)  One of the good things about PowerShell, there\’s usually an alternative way.  I always look at MOW\’s posts and wonder why I didn\’t think of that!
     
     

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s