欧拉计划 #17 Ruby - 怎么了?

Project Euler #17 Ruby - What's wrong?

我在 Ruby 中编写了一个程序,但我不知道为什么它没有给我正确的答案

问题: 如果数字1到5用单词写出来:一、二、三、四、五,那么总共用了3 + 3 + 5 + 4 + 4 = 19个字母。

如果把1到1000(一千)的数字全部用文字写出来,要用多少个字母?

注意:不要计算空格或连字符。例如,342(三百四十二)包含 23 个字母,115(一百一十五)包含 20 个字母。在写数字时使用 "and" 符合英国的用法。

我的代码:

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

正确答案是

21124

我真的不知道Ruby,但我知道这个欧拉问题。在研究了您的代码后,我不得不猜测您的 else 语句不正确。

假设您有数字 111,我认为它属于您的 else 语句。您最终构建了一个字符串 "onehundredandtenone" 而不是 "onehundredandeleven"

所以在我看来,从 111 到 119 的范围内构建的字符串不正确,这会影响您的计数。实际上,对于 211 - 219... 311 - 319... 等...

你可以使用人性化 gem:

require 'humanize'

p (1..1000).to_a.map(&:humanize).join.tr(" -", "").size

不知道你是否已经知道哪里出了问题,我调试了一下。

问题发生在111-120、211-220、311-320左右... 例如。 number_to_words(111) 变成了 "onehundredandtenone"

所以我又添加了两行来考虑这些实例。

修改如下:

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
    string = "onethousand"
elsif n >= 100 && n % 100 == 0 
    string = custom[n.to_s[0]] + "hundred"
#changed this part
elsif n >= 100 && (n % 100 < 20)
    string = custom[n.to_s[0]] + "hundred" + "and" + custom[(n % 100).to_s[(0..1)]] 
else
    string = custom[n.to_s[0]] + "hundred" + "and" + tens[n.to_s[1]] + custom[n.to_s[2]]
    end
    return string
end