Scripting Games 2007 Advanced PowerShell Event 1 and 2
As the Anwers to the First 2 events in the Scripting Games 2007, Are Posted
I will post my solutions to the Advanced PowerShell events 1 and 2.
As I allready did a PowerShell Function doing a conversion the other way around Converting Hindu-Arabic numerals to Roman Numberals
PoSH>format-Roman 1987
MCMLXXXVII
PoSH>format-Roman 1999
MCMXCIX
Also I made a TypeExtenstion so you can use it like this :
PoSH> (get-date).year
2007
PoSH> (get-date).year.ToRoman()
MMVII
PoSH>
I posted both the Script version and the TypeExtension file on both my current as my former blog for format testing before I did see the Scripting games Program
you can find this here : Code formatting test , that made a good starting
When I started the event, I did first think of a a bit funnier Solution using the Voice API for it
Read-Host "Roman" |% {(new-object -com SAPI.SpVoice).speak($_)}
But I did not know if the Scripting Guy's would have there speaker on, and it has some funny problems see examples :
PoSH> (new-object -com SAPI.SpVoice).speak("CMXXV")
1
PoSH> Read-Host "Roman" |% {(new-object -com SAPI.SpVoice).speak($_)}
Roman: IV
1
PoSH> Update-TypeData C:\PowerShell\TypeData\TypedataInt32.ps1xml
PoSH> 1..12 |% {$_.toRoman()}
I
II
III
IV
V
VI
VII
VIII
IX
X
XI
XII
PoSH> 1..12 |% {(new-object -com SAPI.SpVoice).speak($_.toRoman())}
Or for some more examples
(new-object -com SAPI.SpVoice).speak("Scripting Games MMVII")
(new-object -com SAPI.SpVoice).speak("MVII")
(new-object -com SAPI.SpVoice).speak("MMVII")
(new-object -com SAPI.SpVoice).speak("MM VII")
So I followed the logic of my former solution and processed and remove the "double" digits (4-IV,9-IX) first
basicly I copied and Pasted a couple block of code like this together for all the combinations
$num = [regex]::Matches($Roman,'CM').count * 900
$roman = $Roman.Replace('CM','')
$num += [regex]::Matches($Roman,'M').count * 1000
did, a bit dirty but .. did the job
As the scripting guy's PS Answer: Do as the Romans Do (or Did) , is better constructed I leave it with that
* Edit* got 2 better solutions while discussing answer on IRC (freenode #PowerShell ) :
http://rafb.net/p/DTCoEh87.html
http://gaurhothw.spaces.live.com/blog/cns!52B0837064D0B275!137.entry
I can be Short about it :
$i = '' ;do {$i += '4'} until ($i %3 -eq 0) ; $i / 3
And look Mum without Spaces ;-)
PoSH> $i='';do{$i+='4'}until($i%3-eq0);$i/3
148
PoSH>
I first make sure $i is a string, and keep adding 4's to it till I get a Modulus %3 back of 0 and print that value divided by three.
Ok maybe a bit cryptic but than again : PS Answer: Three by Fours , against
$i = ''
do {
$i += '4'
} until ($i % 3 -eq 0)
$i / 3
and by going the other way around I think this way is a bit less "Brute Force" so maybe thiny is not allway less ;-)
Enjoy,
Greetings /\/\o\/\/