Monday, August 16, 2010

Project Euler and PowerShell - Problem 42

Here is a PowerShell solution to Project Euler - Problem 42.
# Download the text file and create the array            
$web = New-Object System.Net.WebClient
$url = "http://projecteuler.net/project/words.txt"
$words = $web.DownloadString($url).replace("""","").split(",")

# Generate a list of Triangular numbers
[int[]]$triNums = @()
for($r=1;$r -lt 500; $r++) {
$triNums += $r*($r+1)/2
}

# Create a hashtable for numeric lookup
$lookup = @{}
$i=1
65..90 | Foreach {$lookup.add([Char]$_,$i++)}

# Get the numeric value of a word
function Get-WordValue($word) {
$letters = $word.ToCharArray()
$sum = 0
foreach ($letter in $letters) {
$sum += $lookup[[char]$letter]
}
return $sum
}

# Count the Triangular words
$Count = 0
foreach ($word in $words) {
if($triNums -contains (Get-WordValue $word)) {
#"{0}`t{1}" -f (Get-WordValue $word), $word
$Count++
}
}
$count