我已經盯住了我的代碼超過一個小時了,每次都要反覆檢查每個方法。但是,這個非常錯誤的代碼看起來是正確的,我不知道哪個部分有錯誤。任何洞見你們可以給予不勝感激。Ruby中的項目Euler#17,我的(錯誤的)答案對我來說是合乎邏輯的
問題:
如果1至5中的話寫出的數字:一個,兩個,三個,四個,五個,則有3 + 3 + 5 + 4 + 4 = 19個總的字母。
如果所有從1到1000(單萬)的數字包容性話寫出來,多少個字母,會使用嗎?
@ones = [3, 3, 5, 4, 4, 3, 5, 5, 4]
@teens = [6, 6, 8, 8, 7, 7, 9, 9, 8] #without "ten"
@tens = [6, 6, 6, 5, 5, 7, 6, 6] #also without "ten"
@hundred = 7
@hundred_and = 10
@one_thousand = 11
def sum_array(array)
array.inject { |sum, n| sum + n }
end
def one_to_nineteen
sum_array(@ones) + sum_array(@teens) + 3 #ten
end
def sum_tens
sum = 0
@tens.each { |x| sum += sum_array(@ones) + (x * 10) } #0-9
return sum
end
def one_to_ninety_nine
return one_to_nineteen + sum_tens
end
def sum_hundreds
sum = 0
@ones.each do |x|
sum += (x + @hundred) + ((x + @hundred_and) * one_to_ninety_nine) + one_to_ninety_nine
end
return sum
end
def one_to_one_thousand
print one_to_ninety_nine + sum_hundreds + @one_thousand
end
one_to_one_thousand
這輸出:117750,(在網上查找答案後)是完全錯誤的。
作爲參考,什麼是所期望的輸出?你(用你的方法)爲數字1-10寫了一個程序並測試了它嗎?並移動到1-100,然後1-1000等可能幫助。 –
我只是試圖做到這一點,我也搞砸了,雖然我得到了15752 ... – Charles
所需的輸出是:21124 而我測試了1-10的方法。 –