Scriptinggames2007redux
From Terminal23wiki
This page is a revisit of some of the advanced challenges from the 2007 Winter Scripting Games. My goal here is to rewrite my scripts to be a little bit better and far shorter using different techniques based on other responses and answers (which will not always be linked to or credited). I will try to stay true to my original logic, but sometimes alternative logics do the job better. I just want to explore rewriting these as part of my own growing affinity to PowerShell.
Advanced Event 2
I really stepped this event answer out originally, but a lot of it turned out to be redundant and unnecessary. I whittled this down a bit until I came up with this, which is pretty much what MoW and Gaurhoth came up with. Build a string of 4's until they are evenly divisible by 3. PowerShell doesn't necessarily need to be prompted on what type a variable is. It will morph the variable as needed depending on the context it is used. A string of '444' when used as part of a math expression will be treated as an int. Convenient!
do { [string]$a += 4 } until ($a % 3 -eq 0)
$a / 3
Like I said, we don't necessarily have to declare $a as string, although we do need to make sure it concatonates 4s as opposed to adds them. This would also work for a few less characters.
do { $a += '4' } until ($a % 3 -eq 0)
$a / 3
Advanced Event 4
My original logic could have been dramatically simplified by realizing that any year divided by 12 will yield a remainder (modulus) from 0 to 12. By re-ordering the given series of animals, this is really all the calculation needed to get an answer. For instance, 1977 divided by 12 yields a remainer of 6 and 1977 should be the year of the snake.
In addition, an array can be quickly generated using a quick function trick to avoid typing all the quotation marks.
function instant-array {$args}
$years = instant-array Monkey Rooster Dog Pig Rat Ox Tiger Rabbit Dragon Snake Horse Goat
$y = Read-Host "Enter a year:"
$animal = $y % 12
Write-Host $years[$animal]
Of course, MoW is the ultimate and reduces the lines even more by using the split method. He splits a string into an array and uses a one-liner to spit out the results. I borrowed his style and reduced the logic involved.
$years = "Monkey Rooster Dog Pig Rat Ox Tiger Rabbit Dragon Snake Horse Goat".Split(' ')
$y = Read-Host "Enter a year:"
$years[($y % 12)]
