This continues my series of solution posts for the 2008 Scripting Games with my solution for the Beginner’s Event 6. This was actually the script that got me started solving the beginner scripts — someone asked about it in the first couple days of the scripting games, and it got me interested.
The challenge was to take a series of coffee “orders” from a text file, and turn them into a single order. In the text file they’re written in the format:
Office 101
Espresso 10
Latte 2
Cappuccino 4
So each office number has an order consisting of some number of Espressos, Lattes, and Cappuccinos.
MoW and the Scripting Guys seemed to have the same general idea here, to use a hash array. They each did a little bit more work than was strictly necessary, so here’s how I would have done that.
$orders = @{}
gc C:\Scripts\coffee.txt | Where { $_ -notlike "Office*" } | ForEach {
$drink,[int]$count = $_.Split();
$orders[$drink] += $count;
}
ft -in $orders -h
The key difference in my solution is that I didn’t initialize the $orders hashtable (because it doesn’t need to be initialized) and I filtered out the “Office” lines as early as possible to avoid processing them through the rest of the code — when you’re writing PowerShell pipeline scripts, always remember that you want to filter as early as possible.
However, I have to admit, that’s not how I solved it. Instead, I used Select-Object to create custom objects, grouped them, and then measured the sum of the “Count” property of the orders in each group:
gc C:\Scripts\coffee.txt | Where { $_ -notlike "Office*" } |
Group {$_.split()[0]} |
Format-Table Name, @{l="Count";e={($_.Group | ForEach {$_.split()[1]} | Measure-Object -Sum).Sum}} -Auto -h
You’ll notice that this isn’t as effective as the other solution: it has to do the split() twice, and basically groups everything and then un-groups it to get the count… but it’s the way I think: one command-line — a big long pipeline — instead of a foreach loop with multiple lines in it. By now you won’t be surprised to know that I compared the speeds of these, and the first approach runs in just about half the time of the second one.
Hey, guess that you not know how slow our coffee machine is
no need for speed on this one hehe
Greetings /\/\o\/\/