def parse_words file = File.open('p042_words.txt') words = file.read.delete('"').split(',') file.close words end def perfect_square?(n) Math.sqrt(n) % 1 == 0 end def triangle_number?(n) perfect_square?((8 * n) + 1) end ALPHABET = { '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 } def triangle_word?(word) triangle_number?(word.split('').map { |c| ALPHABET[c] }.inject(:+)) end def count_triangle_words parse_words.select { |w| triangle_word?(w) }.count end