Project Euler Problem #17

February 3, 2010

Read the details of the problem here


How many letters would be needed to write all the numbers in words from 1 to 1000?


This isn’t actually too bad to just solve on paper but, in the spirit of the problem, here’s a Groovy something that constructs a dictionary of the words up to one thousand omitting whitespace.

def words = [
    0:"", 1:"one", 2:"two", 3:"three", 4:"four", 5:"five",
    6:"six", 7:"seven", 8:"eight", 9:"nine", 10:"ten",
    11:"eleven", 12:"twelve", 13:"thirteen", 14:"fourteen",
    15:"fifteen", 16:"sixteen", 17:"seventeen", 18:"eighteen",
    19:"nineteen", 20:"twenty", 30:"thirty", 40:"forty",
    50:"fifty", 60:"sixty", 70:"seventy", 80:"eighty",
    90:"ninety", 1000:"onethousand" ]

1.upto(999) {
  if (!words[it]) {
    if (it < 100) {
      words[it] = words[it.intdiv(10) * 10] + words[it % 10]
    else {
      words[it] = "${words[it.intdiv(100)]}hundred"
      def r = it % 100
      if (r > 0) words[it] += "and${words[r]}"

def answer = words.values()*.size().sum()

A fun little problem to do. Note that, although the problem doesn’t need it, adding in a empty string for zero avoids some code that would otherwise have to deal with zero values. It runs in 0.69 seconds.


Quick and easy to write in Groovy. Wouldn’t actually be much much more complex or verbose to do in Java using the same algorithm. The Groovy listops made it easy to do the final summation of the word lengths.


Leave a Reply

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

You are commenting using your 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: