Euler Solution 42

From ProgSoc Wiki

Jump to: navigation, search

Solutions for Problem 42

How many triangle words does this list of common English words contain?

Ruby by tomchristmas

Runtime: 97ms (on kali).

words = []
tri_words = 0

File.open("words.txt", "r"){|f|
   f.each{|line|
     words = line.chop.reverse.chop.reverse.split("\",\"")
   }    
}

words.each{|w|
   total = 0

   # obtain 1-26 value for each letter by subtracting from their ASCII value
   w.each_byte{|c| total += (c - 64)} # popular 80s home computer

   # famous quadratic formula
   # solving tri_index ^ 2 + tri_index - (2 * total) == 0 for tri_index > 0
   tri_index = (-1 + Math.sqrt(1 + (4 * (2 * total)))) / 2.0

   # classic integer test
   tri_words += 1 if tri_index.floor == tri_index.ceil 
}

puts tri_words

Python by Althalus

Runtime: 41 ms

import time
from math import sqrt
start_time = time.time()

def word_score(word):
        letter_values = {
                'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5, 'F': 6, 'G': 7, 'H': 8, 'I': 9, 'J': 10,
                'K': 11, 'L': 12, 'M': 13, 'N': 14, 'O': 15, 'P': 16, 'Q': 17, 'R': 18, 'S': 19,
                'T': 20, 'U': 21,  'V': 22, 'W': 23, 'X': 24, 'Y': 25, 'Z': 26,
        }
        score = 0
        for c in word:
                try:
                        score +=letter_values[c]
                except KeyError: pass
        return score

#build a list of 50 triangular numbers.
triangles = [0.5*n*(n+1) for n in range(1,50)]

total = 0
file = open('words.txt','r')
words = file.readlines()
file.close()
for word in words:
        if word_score(word) in triangles:
                total+=1

print total
run_time = time.time() - start_time
print run_time

(modified the list by s/"//g and s/,/\r/g first.)

Personal tools