Euler Problem 17 – Number letter counts

Number letter counts

Problem 17

If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.

If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?

NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of “and” when writing out numbers is in compliance with British usage.

 As the question explains, we need to write numbers in words and count the number of all the characters for first 1000 numbers. As soon as I read this I googled “convert numbers to words in R”. I got this link. Now I had two options , to use this function as it is or write my own new function. I tested this function for few numbers and it worked fine , so I went ahead using this function. I preferred using this function as it is,  partly because it would take a lot of time to understand and to cover all the possible corner cases and partly because I was too lazy to write one myself :P. I could definitely write my own function but that is not the main problem which we are trying to solve.

So now, I have a function which returns words for the numbers entered. Now I just need to find generate a sequence for first 1000 numbers, pass it to this function and count the number of characters.

 
countNumberOfCharactersInASeries = function(x) {
  sum(nchar(gsub(" ", "", numbers2words(seq(x)))))
}
countNumberOfCharactersInASeries(1000)
#[1] 21124

So, I made a function where you enter the maximum number till which you want to count the characters, generate a sequence (seq) till that number, apply the function (numbers2words) to all those numbers. Now we need to ignore the spaces and hyphens if any. Luckily this function does not generate any hyphens, so I just replace the spaces with empty string (gsub), count the number of characters (nchar) and then sum them.

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