// you’re reading...
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading ... Loading ...

Project Euler Solutions

Project Euler 42 Solution

Project Euler 42 Solution

Project Euler 42: How many triangle words does the list of common English words contain?

Problem Description

The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, …

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 19 + 11 + 25 = 55 = t10. 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?

Analysis

Remember Problems 44 & 45? The same logic applies except for triangle numbers. Whenever the equation ( √(1+8n) – 1 ) / 2 evaluates to an integer the number, n, is a triangle number.

Remember Problem 22? Well, this is the same core solution.

Solution

Runs < 0.01 second in Perl.

$c = 0;
@h{'A' .. 'Z'} = (1 .. 26);
open (IN,"<words.txt") or die "Can't open file: $!";
@words = map { /"(w+)"/  } split /,/,<IN>;
 
foreach ( grep { is_tri(score($_)) } @words) {$c++}
 
print "Answer to PE42 = $c";
 
sub is_tri {my $n=shift; my $t=(sqrt(1+8*$n)-1)/2; return int($t) == $t }
sub score {my $score=0; $score+=$_ for @h{map uc, split //,shift}; return $score };

Comments

Even though we used Perl, we still kept it readable, mostly.

Discussion

No comments yet.

Post a comment