Project Euler Problem #22

February 9, 2010

Read the details of the problem here

Summary

What is the total of all the name scores in the file of first names?

Solution

Just a programming question rather than anything mathematical.

def (answer, BASE_CHAR) = [ 0, ((char)'A').charValue() - 1 ]

new File("names.txt")
        .text
        .replaceAll("\"","")
        .split(",")
        .sort()
        .eachWithIndex { name, idx ->
            answer += (idx+1) * name.toList().sum {
                ((char)it).charValue() - BASE_CHAR
            }
        }

Runs in 0.93 seconds. I’ve split the text input preparation code over several lines and added a constant for ease of reading but this is actually almost a two-liner in concept.

Conclusion

Groovy excels at this kind of processing, making it a straight translation of requirement to code. The only slight wrinkle for this particular question is that Groovy interprets all text as Strings so the explicit char casts are necessary.

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: