Showing posts with label Scripting Games 2008. Show all posts
Showing posts with label Scripting Games 2008. Show all posts

Wednesday, March 19, 2008

2008 Scripting games prizes

 

I got an email from Greg Stemp, the Scripting Guy. He notified me that I won a licensed copy of ShellTools' PowerShell Analyzer/PowerShell Plus and a PowerShell T-shirt. I'm also eligible for a Scripting Games Certificate of Excellence. WOW, Thank you!

Wednesday, March 5, 2008

The Third Annual Scripting Games

 

The Third Annual Scripting Games is over. This year's event was full of challenges for everyone, beginners and veteran scripters alike, and included a third (non-Microsoft) scripting language for submitting solutions - Perl.

I've managed to get a perfect score in both Sudden Death Challenge and Advanced PowerShell divisions.

I would also like to congratulate the Scripting Guys for a well designed and well organized event. This year's event was much harder and more challenging than previous years. I'm curious to see what they have up their sleeve for next year's event, can't wait!

By the way, until the 2009 games, if you're looking for a 24x7 real world PowerShell challenge - I know the right place... Join the microsoft.public.windows.powershell newsgroup and sharpen your PowerShell skills and knowledge.

2008 Scripting Games - Advanced Event 9

Event 9: You’re Twisting My Words

 

$content = [System.IO.File]::ReadAllText("C:\Scripts\alice.txt")
$reversed = $content.split() | foreach {"$($_[($_.length-1)..0])" -replace " " }
[string]::Join(" ",$reversed)

resuoiruC' dna '!resuoiruc deirc ecilA ehs( saw os hcum ,desirprus taht rof eht tnemom ehs etiuq togrof woh ot kaeps doog ;)hsilgnE won' m'I gninepo tuo ekil eht tsegral epocselet taht reve !saw ,eyb-dooG '!teef rof( nehw ehs dekool nwod ta reh ,teef yeht demees ot eb tsomla tuo fo ,thgis yeht erew gnitteg os raf .)ffo ,hO' ym roop elttil ,teef I rednow ohw lliw tup no ruoy seohs dna sgnikcots rof uoy ,won ?sraed m'I erus _I_ t'nahs eb !elba I llahs eb a taerg lae
d oot raf ffo ot elbuort flesym tuoba :uoy uoy tsum eganam eht tseb yaw uoy ;nac tub-- I tsum eb dnik ot ',meht thguoht ,ecilA ro' spahrep yeht t'now klaw eht yaw I tnaw ot !og teL em :ees ll'I evig meht a wen riap fo stoob yreve '.samtsirhC

2008 Scripting Games - Advanced Event 10

Event 10: Blackjack!

 

$cards = "ah", "ac", "ad", "as",
       "2h", "2c", "2d", "2s",
       "3h", "3c", "3d", "3s",
       "4h", "4c", "4d", "4s",
       "5h", "5c", "5d", "5s",
       "6h", "6c", "6d", "6s",
       "7h", "7c", "7d", "7s",
       "8h", "8c", "8d", "8s",
       "9h", "9c", "9d", "9s",
       "th", "tc", "td", "ts",
       "jh", "jc", "jd", "js",
       "qh", "qc", "qd", "qs",
       "kh", "kc", "kd", "ks"

function resolve-cardSign([string]$str){
    switch($str.substring(1,1)){
        "d" {"Diamonds"; break}
        "c" {"Clubs"; break}
        "s" {"Spades"; break}
        "h" {"Hearts"; break}
    }
}

function resolve-cardName([string]$str){
    switch($str.substring(0,1)){
        "a" {"Ace"; break}
        "2" {"Two"; break}
        "3" {"Three"; break}
        "4" {"Four"; break}
        "5" {"Five"; break}
        "6" {"Six"; break}
        "7" {"Seven"; break}
        "8" {"Eight"; break}
        "9" {"Nine"; break}
        "t" {"Ten"; break}        
        "j" {"Jack"; break}
        "q" {"Queen"; break}
        "k" {"King"; break}    
    }
}

function resolve-cardValue([string]$str){
    switch($str.substring(0,1)){
        "a" {11; break}
        {$_ -match "[tjqk]"} {10; break}
        default {$_}
    }
}

function shuffle-deck{
    $max=$deck.count-1
    for ($i = 0; $i -le $max;$i++) {
        $r = $rnd.next($max)
        $deck[$i],$deck[$r] = $script:deck[$r],$script:deck[$i]
    }
}

function deal-user($num){
    1..$num | foreach {
        $r = $rnd.next($deck.count)
        $cardName = "{0} of {1}" -f (resolve-cardName $deck[$r]),(resolve-cardSign $deck[$r])
        $script:userCards+=$cardName
        $script:user+= resolve-cardValue $deck[$r]
        [void]$deck.removeAt($r)
    }
}

function deal-dealer($num){
    1..$num | foreach {
        $r = $rnd.next($deck.count)
        $cardName = "{0} of {1}" -f (resolve-cardName $deck[$r]),(resolve-cardSign $deck[$r])
        $script:poshCards+=$cardName
        $script:posh+= resolve-cardValue $deck[$r]
        [void]$deck.removeAt($r)
    }
}    

function print-hands([switch]$reveal){
    "`nYour cards:"
    "-----------"
    $script:userCards
    "`nDealer's cards:"
    "---------------"
    
    if($reveal){
        $script:poshCards
    } else {
        "?"
        $script:poshCards[1..($script:poshCards.length)]
    }
    
    "`n"
}


#########
cls
$rnd = New-Object System.Random (get-date).millisecond
$user=0
$posh=0
$userCards=@()
$poshCards=@()

$deck = new-object system.collections.arraylist
$cards | foreach { [void]$deck.add($_) }
shuffle-deck 

deal-user 2
deal-dealer 2
$host.ui.RawUI.WindowTitle = "user: $user, posh $posh"
print-hands
    
# while user score are less then 21 and user wants another card
while(($user -lt 21) -and ((read-host "Stay (s) or hit (h) ?") -eq "h")){
    deal-user 1
    $host.ui.RawUI.WindowTitle = "user: $user, posh $posh"
    "`nYou have $user`n"

    if($user -eq 21) {print-hands -reveal; "You win."; return}
    
    if($user -gt 21) {
        print-hands -reveal
        "`nOver 21. Sorry, you lose."
        return
    }

    if(($user -eq 21) -and ($posh -eq 21)) {
        print-hands -reveal
        "`nYou have $user,`nThe dealer has $posh. Ties (pushes) go the dealer. Sorry, you lose."
        return
    } 
    
    $script:userCards
    
    #$script:userCards; "You win."; return

}

"You have $user`n"

# if dealer's hand is greather than users hand then the dealer wins
if(($posh -gt $user) -and ($posh -le 21)) {
    print-hands -reveal
    "`nYou have $user.`nThe dealer has $posh. Sorry, you lose."; return
} 

while($posh -lt $user) {deal-dealer 1}

# final results
if($posh -eq $user) {
    "`nYou have $user,`nThe dealer has $posh. Ties (pushes) go the dealer. Sorry, you lose."
    return
} 

print-hands -reveal
if(($posh -gt $user) -and ($posh -le 21)){
    "`nThe dealer has $posh. You have $user, You lose."
} else {
    "`nThe dealer has $posh. You have $user, You win."
}

Saturday, March 1, 2008

Sudden Death Challenge: Event 9

 

(cat C:\Scripts\symbols.txt) -replace '[^a-zA-Z0-9 ]'

# result

The 2008 Winter Scripting Games

Thursday, February 28, 2008

2008 Scripting Games - Advanced Event 8

 

Event 8: Making Beautiful Music

 

$TotalMusicTime = New-TimeSpan

$songList = cat C:\Scripts\songlist.csv | foreach {
    $item = $_.split(",")
    $time = $item[2].split(":")
    $song = new-object psobject
    add-member -inp $song noteproperty Artist $item[0]
    add-member -inp $song noteproperty SongName $item[1]
    add-member -inp $song noteproperty Minutes $time[0]
    add-member -inp $song noteproperty Seconds $time[1]
    $song    
}

$cd=@()

$singleArtist = $songList | group Artist | where {$_.count -eq 1}
$groupsArtist = $songList | group Artist | where {$_.count -gt 1}
$singleArtist | foreach {
    $song = new-object psobject
    add-member -inp $song noteproperty Artist $_.Group[0].Artist
    add-member -inp $song noteproperty SongName $_.Group[0].SongName
    add-member -inp $song noteproperty Minutes $_.Group[0].Minutes
    add-member -inp $song noteproperty Seconds $_.Group[0].Seconds
    $cd+=$song
    $TotalMusicTime = $TotalMusicTime.add((New-TimeSpan -Minutes $song.Minutes -Seconds $song.Seconds))
}

$groupsArtist | foreach {
    if(($TotalMusicTime.TotalMinutes -ge 75) -and ($TotalMusicTime.TotalMinutes -le 80)){return}
    $song = new-object psobject
    add-member -inp $song noteproperty Artist $_.Group[0].Artist
    add-member -inp $song noteproperty SongName $_.Group[0].SongName
    add-member -inp $song noteproperty Minutes $_.Group[0].Minutes
    add-member -inp $song noteproperty Seconds $_.Group[0].Seconds
    $cd+=$song
    $TotalMusicTime = $TotalMusicTime.add((New-TimeSpan -Minutes $song.Minutes -Seconds $song.Seconds))
}

write-host
$cd | select Artist,SongName,@{n="Time";e={"{0}:{1}" -f $_.Minutes,$_.Seconds}} | sort artist | ft -a

"Total music time: {0}:{1}" -f $TotalMusicTime.TotalMinutes.ToString("N0"),$TotalMusicTime.Seconds
write-host

 

Artist                      SongName                     Time
------                      --------                     ----
Alice Cooper                I'm Eighteen                 2:58
Badfinger                   No Matter What               2:59
Cracker                     Eurotrash Girl               8:03
Credence Clearwater Revival Have You Ever Seen the Rain? 2:39
Dire Straits                So Far Away                  5:12
Don McLean                  American Pie                 8:35
Donovan                     Catch the Wind               5:02
Jefferson Airplane          White Rabbit                 2:34
John Prine                  New Train                    3:24
Nick Cave and the Bad Seeds Deanna                       3:46
Nirvana                     Heart-Shaped Box             4:41
Paul Simon                  Mother and Child Reunion     2:48
REM                         Losing My Religion           4:28
Robert Palmer               Simply Irresistible          4:12
The Animals                 House of the Rising Sun      4:31
The Bangles                 Manic Monday                 3:06
The Beatles                 Help                         2:18
The Kinks                   Sunny Afternoon              3:36
The Ramones                 I Wanna Be Sedated           2:29


Total music time: 77:21

2008 Scripting Games - Advanced Event 7

 

$teams = "A","B","C","D","E","F"
$rounds=@()

for($i=0; $i -lt $teams.length; $i++){
   0..2 | foreach { $rounds += ("{0} vs. {1}" -f $teams[$_],$teams[-($_+1)]) }
   1..($teams.length-1) | foreach { $teams[1],$teams[$_] = $teams[$_],$teams[1] }
} 

# remove duplicates
$rounds = $rounds | select -unique

# random positions
$rnd = new-object random (get-date).millisecond 
$list = new-object System.Collections.ArrayList
$list.AddRange(0..($rounds.count-1))

1..$rounds.count | foreach {
   $n=$rnd.next($list.count)	
   $rounds[$list[$n]]
   [void]$list.removeAt($n)
}



#result

B vs. E
A vs. C
C vs. D
A vs. E
F vs. D
C vs. F
D vs. B
F vs. B
B vs. C
A vs. D
A vs. B
A vs. F
E vs. F
E vs. C
D vs. E

Sudden Death Challenge: Event 7

 

([math]::Sqrt(([math]::Pow(([math]::Truncate((100*2)/30)),5) *4)) /45).toString("N2")

 

#Result

3.92

Sudden Death Challenge: Event 6

 

$words = (cat c:\scripts\lettercase.txt).split(" ") | foreach {
    if($_ -match '\d+') {
        $_= [int]$_ -1111; $_
    } else {
        $_= $_[0].toString().toUpper()+$_.substring(1).toLower(); $_
    }
}

[string]::join(" ",$words)

 

# result

The 2008 Winter Scripting Games!

Sudden Death Challenge: Event 5

 

# one line

gwmi -list | ? {$_.name -like "WIN32_*"} | % {$_.psbase.properties} | ? {($_.name[0] -cmatch '[A-Y]') -and ($_.origin -like "WIN32_*")} | group {$_.name[0]} | sort name | select @{n="Name";e={$_.group[0].name}},@{n="Class";e={$_.group[0].origin}} | ft -auto


# results
Name                      Class                               
----                      -----                               
ArpAlwaysSourceRoute      Win32_NetworkAdapterConfiguration   
Bias                      Win32_TimeZone                      
ColorPlanes               Win32_DisplayControllerConfiguration
DriveName                 Win32_VolumeChangeEvent             
EventType                 Win32_PowerManagementEvent          
FileName                  Win32_ModuleLoadTrace               
GatewayCostMetric         Win32_NetworkAdapterConfiguration   
HorizontalResolution      Win32_DisplayControllerConfiguration
ImageBase                 Win32_ModuleLoadTrace               
JavaClass                 Win32_ClassicCOMClassSetting        
KeepAliveInterval         Win32_NetworkAdapterConfiguration   
LastDrive                 Win32_BootConfiguration             
MachineName               Win32_ComputerSystemEvent           
NumForwardPackets         Win32_NetworkAdapterConfiguration   
OEMEventCode              Win32_PowerManagementEvent          
ProcessID                 Win32_ModuleLoadTrace               
QuotaNonPagedPoolUsage    Win32_Process                       
RemainingEvaluationPeriod Win32_WindowsProductActivation      
StackBase                 Win32_ThreadStartTrace              
Type                      Win32_ComputerShutdownEvent         
UserStackBase             Win32_ThreadStartTrace              
VerticalResolution        Win32_DisplayControllerConfiguration
WaitMode                  Win32_ThreadStartTrace              
XOffCharacter             Win32_SerialPortConfiguration       
YResolution               Win32_PrinterConfiguration          


Sudden Death Challenge: Event 3

 

$presidents= cat C:\Scripts\presidents.txt | foreach {
    $tmp = $_.split(",")
    $p=New-Object psobject
    Add-Member -inp $p noteproperty firstName $tmp[1].trim()
    Add-Member -inp $p noteproperty lastName  $tmp[0].trim()
    Add-Member -inp $p noteproperty firstLength $p.firstName.length
    Add-Member -inp $p noteproperty vowels @(("{0}{1}" -f $p.firstName,$p.lastName).toCharArray() -match '[aeiou]').count
    $p
}


$longest = $presidents | sort firstLength -desc | select -first 1
"Longest first name: {0} {1}" -f $longest.firstName,$longest.lastName

"Total vowels used: {0}" -f ($presidents | measure-object vowels -sum).sum


$initials = ""
$alphabet = ([string](65..90 | foreach {[char]$_})).replace(" ","")

$presidents  | foreach {
    $initials+="{0}{1}" -f $_.firstName[0],$_.lastName[0]
}

$alphabet = $alphabet -replace "[$initials]"
"The following letters are not used as Presidential initials:"
$alphabet.ToCharArray()

 

 

# results

Longest first name: Rutherford Hayes
Total vowels used: 192
The following letters are not used as Presidential initials:
I
O
Q
S
X
Y

Sudden Death Challenge: Event 2

 
$vertical = @(cat C:\Scripts\vertical.txt) 
$text=""

for($i=0; $i -le 3; $i++){
    0..($vertical.length-1) | foreach { $text+=$vertical[$_][$i] } 
}

$text
 
# result
The 2008 Winter Scripting Games!

Sudden Death Challenge: Event 4

 

$s = "6882463283678273808479"
for($i=0; $i -lt ($s.length/2); $i++) {write-host -noNew ([char][int]$s.substring(($i*2),2))}

 

#result

DR. SCRIPTO

Wednesday, February 27, 2008

2008 Scripting Games - Advanced Event 6

 

Event 6: Prime Time

 

function Test-Prime ($num){ 

  $prime = new-object psobject
  add-member -inp $prime noteproperty Number $null
  add-member -inp $prime noteproperty IsPrime $true

  $prime.Number=$num
  
  if($num -eq 2) {
    $prime.IsPrime=$true
  } else {
    foreach ($i in 2..([math]::Sqrt($num))) {
      if ($num % $i -eq 0) {$prime.IsPrime=$false }
    }
  }
  
  $prime  
}
  
1..200 | foreach {Test-Prime $_} | Where {$_.IsPrime} | select number | ft -auto
 

Number
------
     2
     3
     5
     7
    11
    13
    17
    19
    23
    29
    31
    37
    41
    43
    47
    53
    59
    61
    67
    71
    73
    79
    83
    89
    97
   101
   103
   107
   109
   113
   127
   131
   137
   139
   149
   151
   157
   163
   167
   173
   179
   181
   191
   193
   197
   199

2008 Scripting Games - Advanced Event 5

Event 5: You Call That a Strong Password?

param(
  [string]$pwd = $(throw "Please specify password"),
  [string]$wordList = "c:\scripts\WordList.txt"

)

$score=13

$ptrn6 = '(.*).{10,20}' ; if($pwd -notmatch $ptrn6) {$score-=1; "Password is less than 10 characters or less than 20 characters"}


$ptrn7 = '\d' ; if($pwd -notmatch $ptrn7) {$score-=1; "Password must contain at least one number"} $ptrn8 = '[A-Z]' ; if($pwd -cnotmatch $ptrn8) {$score-=1; "No uppercase letters in password."} $ptrn9 = '[a-z]' ; if($pwd -cnotmatch $ptrn9) {$score-=1; "No lowercase letters in password."} $ptrn10 = '(?=.*[^A-Za-z0-9])' ; if($pwd -notmatch $ptrn10) {$score-=1; "Password must contain at least one symbol"} $ptrn11 = '[a-z]{4,}' ; if($pwd -cmatch $ptrn11) {$score-=1; "Four consecutive lowercase letters in password."} $ptrn12 = '[A-Z]{4,}' ; if($pwd -cmatch $ptrn12) {$score-=1; "Four consecutive uppercase letters in password."} if ($pwd.ToCharArray() | group | where {$_.count -gt 1}) {$score-=1; "Duplicate letters in password."} $words = cat $wordList if($words -contains $pwd) {$score-=1; "Password can't be an actual word"} if($words -contains $pwd.substring(0,($pwd.length-1))) {$score-=1; "Password minus the last letter, is an actual word"} if($words -contains $pwd.substring(1)) {$score-=11; "Password minus the first letter, is an actual word"} if($words -contains ($pwd -replace 'O','0')) {$score-=1; "Password substitute 0 (zero) for the letter o (either an uppercase O or a lowercase o)"} if($words -contains ($pwd -replace 'L','1')) {$score-=1; "Password does not simply substitute 1 (one) for the letter l (either an uppercase L or a lowercase l)"} Write-Host switch($score){ {$_ -lt 7} {"A password score of $score indicates a weak password."; break} {($_ -ge 7) -and ($_ -le 10)} {"A password score of $score indicates a moderately-strong password"; break} {$_ -ge 11} {"A password score of $score indicates a strong password."; break} }

Monday, February 25, 2008

2008 Scripting Games - Advanced Event 4

Event 4: Image is Everything

 

function print-calendar($dte){
  
  $month,$year = $dte.split("/")
  $dtfi = new-object system.globalization.datetimeformatinfo
  $AbbreviatedDayNames=$dtfi.AbbreviatedDayNames | foreach {" {0}" -f $_}

  $header= "$($dtfi.MonthNames[$month-1]) $year"
  write-host $header
  
  write-host ([string]::join("",$AbbreviatedDayNames))
  $daysInMonth=[datetime]::DaysInMonth($year,$month)

  $dayOfWeek =(new-object datetime $year,$month,1).dayOfWeek.value__
  $today=(get-date).day
  
  for ($i = 0; $i -lt $dayOfWeek; $i++){write-host (" "*4) -nonew}
  for ($i = 1; $i -le $daysInMonth; $i++)
  {
    if($today -eq $i){write-host ("{0,4}" -f $i) -nonew}
    else {write-host ("{0,4}" -f $i) -nonew}

      if ($dayOfWeek -eq 6) {write-host}
      $dayOfWeek = ($dayOfWeek + 1) % 7
  }
  if ($dayOfWeek -ne 0) {write-host}
}

print-calendar 2/2008
 
February 2008
 Sun Mon Tue Wed Thu Fri Sat
                       1   2
   3   4   5   6   7   8   9
  10  11  12  13  14  15  16
  17  18  19  20  21  22  23
  24  25  26  27  28  29
 
 
 
 
 
 

2008 Scripting Games - Advanced Event 3

 

Event 3: Instant (Runoff) Winner

$ballots = cat C:\Scripts\votes.txt | foreach {
  $tmp = $_.split(",")
  $ballot = New-Object psobject
  add-member -inp $ballot noteproperty candidat $tmp
  $ballot
}


$totalBallots = $ballots.length

for($i=1; $i -lt 4; $i++){
  $round = $ballots | group {$_.candidat[0]} | sort count -desc | select Name, @{n="Percent";e={"{0:N2}" -f (($_.count/$totalBallots)*100)}}
  
  $first = $round[0]
  if($first.Percent -ge 50){
    "The winner is {0} with {1}% of the vote." -f $first.Name,$first.Percent
    return
  }
  
  $last = $round[-1].Name
  $ballots | foreach {$_.candidat = $_.candidat | where {$_ -ne $last}}
}

The winner is Pilar Ackerman with 50.17% of the vote.

2008 Scripting Games - Advanced Event 2

 

Event 2: Skating on Thin Ice

$winners = cat C:\Scripts\skaters.txt | foreach {
  $item = $_.split(",")
  $scores = $item[1..7] | sort
  
  $skater = new-object psobject
  add-member -inp $skater noteproperty Name $item[0]
  add-member -inp $skater noteproperty HighestScore $scores[-1]
  add-member -inp $skater noteproperty LowestScore $scores[0]
  add-member -inp $skater noteproperty Score (($scores[1..($scores.length-2)] | measure-object -average).Average)
  add-member -inp $skater noteproperty Medal $null
  $skater
  
} | sort Score -desc | select -first 3

$winners[0].Medal="Gold medal"
$winners[1].Medal="Silver medal"
$winners[2].Medal="Bronze medal"

0..2 | foreach { "{0}: {1}, {2}" -f $winners[$_].Medal, $winners[$_].name ,$winners[$_].Score }

Results:
Gold medal: Guido Chuffart, 88.2
Silver medal: Jack Creasey, 85.8
Bronze medal: Cecilia Cornejo, 85.4
 

2008 Scripting Games - Advanced Event 1

 

Event 1: Could I Get Your Phone Number?

It seems I've taken the long path on this event, brute forcing every possible combination, padding all 3 letters to four chars.

 

$phone=Read-Host "Enter 7 digit phone number"
$letters = @{"2"="abc";"3"="def";"4"="ghi";"5"="jkl";"6"="mno";"7"="pqrs";"8"="tuv";"9"="wxyz"}
$numbers = 0..($phone.length-1) | foreach { "{0,-4}" -f $letters["$($phone[$_])"]}

"Computing word from Number, this may take a while..."

$wordList = cat c:\scripts\wordList.txt | where {($_.length -eq 7) -and ($_.substring(0,1) -match "[$($numbers[0])]")}


for($a=0; $a -lt 4; $a++){
    for($b=0; $b -lt 4; $b++){
        for($c=0; $c -lt 4; $c++){
            for($d=0; $d -lt 4; $d++){
                for($e=0; $e -lt 4; $e++){
                    for($f=0; $f -lt 4; $f++){
                        for($g=0; $g -lt 4; $g++){
                                    $word = "{0}{1}{2}{3}{4}{5}{6}" -f $numbers[0][$a],$numbers[1][$b],$numbers[2][$c],$numbers[3][$d],$numbers[4][$e],$numbers[5][$f],$numbers[6][$g]
                                    if($wordList -contains $word) {$wordList | where {$_ -eq $word}; return}
                        }
                    }
                }
            }
        }
    }
}

"Scan completed"