Question
The term of the sequence of triangle numbers is given by, ; so the first ten triangle numbers are:
By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is . If the word value is a triangle number then we shall call the word a triangle word.
Using words.txt (right click and ‘Save Link/Target As…’), a 16K text file containing nearly two-thousand common English words, how many are triangle words?
Haskell
parse :: String -> [String]
parse = words . map replaceComma . filter notQuote where
replaceComma ',' = ' '
replaceComma c = c
notQuote = (/= '"')
alphaIndex :: Char -> Int
alphaIndex c = fromEnum c - 64
alphaScore :: String -> Int
alphaScore = sum . map alphaIndex
triangle :: String -> Bool
triangle str = floor t == ceiling t
where s = alphaScore str
t = (sqrt (fromIntegral (1 + 8*s)) - 1) / 2
main :: IO ()
main = do
str <- readFile "/home/zach/code/euler/042/words.txt"
print $ length $ filter triangle $ parse str
$ ghc -O2 -o triangle-words triangle-words.hs
$ time ./triangle-words
real 0m0.003s
user 0m0.000s
sys 0m0.003s
Python
#!/usr/bin/env python
import os
from string import ascii_uppercase
def letter_value(letter):
return ascii_uppercase.index(letter.upper())+1
def word_value(word):
return sum(letter_value(letter) for letter in word)
def triangle(n):
return int((0.5) * n * (n+1))
def main():
triangle_numbers = [triangle(n) for n in range(1, 100)]
words = [word.strip('"') for word in open(os.path.join(os.path.dirname(__file__), 'words.txt')).read().split(',')]
total = 0
for word in words:
if word_value(word) in triangle_numbers:
total += 1
print(total)
if __name__ == "__main__":
main()