Scripting Games 2008 Event 1
Posted by: Andy Schneider in Games 2008, Powershell, Scripting, Scripting GamesNow that the answers have been posted for the first 2 events, I thought I would share my answer for the first event.
My first version worked but on some queries would take up to 20 plus minutes to crunch to through the 32,000 + words.
Here is what I finally ended up with:
1: $wordlistlocation = "c:\scripts\wordlist.txt"
2: $phonenumber = Read-Host "Please Enter a phone number"
3: $numbers = [char[]]$phonenumber.ToString()
4:
5: filter Get-Letters {
6:
7: switch ($_) {
8: 2 {$letters = "ABC"}
9: 3 {$letters = "DEF"}
10: 4 {$letters = "GHI"}
11: 5 {$letters = "JKL"}
12: 6 {$letters = "MNO"}
13: 7 {$letters = "PRS"}
14: 8 {$letters = "TUV"}
15: 9 {$letters = "WXY"}
16: } # Switch
17:
18: return $letters
19:
20: } #Get-Letters
21:
22: $first,$second,$third,$fourth,$fifth,$sixth,$seventh = $numbers | Get-Letters
23:
24: $string1 = $first[0] + $first[1] + $first[2]
25: $string2 = $second[0] + $second[1] + $second[2]
26: $string3 = $third[0] + $third[1] + $third[2]
27: $string4 = $fourth[0] + $fourth[1] + $fourth[2]
28: $string5 = $fifth[0] + $fifth[1] + $fifth[2]
29: $string6 = $sixth[0] + $sixth[1] + $sixth[2]
30: $string7 = $seventh[0] + $seventh[1] + $seventh[2]
31:
32: $pattern = "^[" + $string1 + "][" + $string2 + "][" + $string3 + "][" + $string4 +"][" + $string5 + "][" + $string6 + "][" + $string7 + "]"
33:
34: Get-Content $wordlistlocation | Select-String -Pattern $pattern | Select -first 1
First I get the content of the wordlist file and then read in a phone number. The cast to an array of char[] was necessary to put them into an array as individual elements. It was interesting that I could not cast to an array of ints, but time was short and I was under pressure, and it worked
Next, I used switch to build a filter that returns the possible letters for any given number. If I pass in a 2, I get back a string of ABC.
Next I used multiple assignment to get all the possibilities for each number.
I used these to build a big ol’ regex pattern. It’s long but relatively simple. Basically just creates 7 chars using the [] for “this OR that OR the other thing.”
For example, if the first two numbers were 2 and 3, it would generate [abc][def] as the pattern.
Once I built up that pattern, I simply used get-content of the word list and piped that to Select-String and gave Select-String the the regex pattern I created.
In my first attempt, I created a list of all possibilities and then did a -match on them and compared to the word list file.
Using regex and Select-String brought my execution time down from 23 minutes to about 7 seconds, give or take.
Entries (RSS)