Search code examples
rubyletters

Project Euler #17 Ruby - What's wrong?


I made a program in Ruby and I have no idea why it's not giving me the correct answer

Problem: 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.

My code:

def number_to_words(n)
    custom = {"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",}
    tens = {"0" => "", "1" => "ten", "2" => "twenty", "3" => "thirty", "4" => "forty", "5" => "fifty", "6" => "sixty", "7" => "seventy", "8" => "eighty", "9" => "ninety"}
    if n < 20 
        string = custom[n.to_s]     
    elsif n >= 20  &&  n < 100      
        string = tens[n.to_s[0]] + custom[n.to_s[1]]
    elsif n % 1000 == 0
        string = "onethousand"
    elsif n >= 100 && n % 100 == 0 
        string = custom[n.to_s[0]] + "hundred"
    else
        string = custom[n.to_s[0]] + "hundred" + "and" + tens[n.to_s[1]] + custom[n.to_s[2]]
    end
end

def letter_counter(x)
    n = 1
    sum = 0
    while n < x + 1
        sum = sum + number_to_words(n).length
        print number_to_words(n).length, "\n"
        n = n + 1
        print n, "\n"
    end
    results = sum
end

Correct answer is

21124


Solution

  • I don't really know Ruby, but I do know this Euler question. After studying your code that you have, I would have to guess that your else statement is incorrect.

    Say you have the number 111, which I think falls into your else statement. You wind up building a string that says, "onehundredandtenone" instead of "onehundredandeleven"

    So it would look to me that the range from 111 - 119 would have incorrect strings built which will throw off your counts. Actually, this would be true for 211 - 219... 311 - 319... etc...