Project Euler Problem #42

April 28, 2010

Read the details of the problem here

Summary

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

Solution

Another one of the text processing problems that Groovy excels at. Not much to say about the solution as it’s all self-explanatory.

def answer =
    new File("euler_p42_words.txt").text
             .replaceAll("\"","").split(",")
             .findAll { word ->
        def wv = word.collect { c -> ((char)c).charValue() - 64 }.sum()
        def sqrt = (int)((wv * 2) ** 0.5)
        sqrt * (sqrt + 1) == wv * 2
    }.size()

This runs in 0.24 seconds.

Conclusion

As mentioned, Groovy is really good to use for solutions like this.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: