这是关于项目欧拉问题#1。当我在 irb 中逐行运行此代码时,我得到了预期的答案,但是当我从 .rb 文件运行它时,它会抛出错误“数组不能被强制转换为 Fixnum (TypeError)”
代码:
# defines the list of integers from 'n' downto 0
def Zi (a, b)
(a.downto b).lazy
end
# the equation numberOfOccurances(smallestMultiple + largestMultiple)/2 gives the sum of all the multiples for a given range
# so, below, multipleCounts[i](multiples[i] + lastMultiples[i])/2 => multipleCounts[i](lastAndFirstMultipleSums[i])/2
# gives the arbitrary sum of multiples of a give number in multiples for the specified range.
def find_sum_for_each_multiple(from, to, *multiples)
myReverseArr = Zi to, from
lastMultiples = multiples.map { |m| myReverseArr.find { |i| i % m == 0 } }
multipleCounts = lastMultiples.zip(multiples).map { |ms| ms.reduce(:/) }
lastAndFirstMultipleSums = lastMultiples.zip(multiples).map { |ms| ms.reduce(:+) }
sumsOfEachMultiple = lastAndFirstMultipleSums.zip(multipleCounts).map { |xs| xs.reduce(:*) }.map { |x| x/2 }
end
def find_sum_of_multiples(from, to, *multiples)
sumsOfEachMultiple = find_sum_for_each_multiple(from, to, multiples)
commonMultiples = []
(0..(multiples.length - 1)).each do |i|
((i+1)..(multiples.length - 1)).each do |j|
commonMultiples << (multiples[i] * multiples[j])
end
end
sumsOfCommonMultiples = find_sum_for_each_multiple(from, to, commonMultiples)
totalSum = (sumsOfEachMultiple.inject { |sum, x| sum + x }) - (sumsOfCommonMultiples.inject { |sum, x| sum + x })
end
puts find_sum_of_multiples(0, 999, 3, 5)
错误信息:
C:\Users\[User]>ruby euler1.rb
euler1.rb:11:in `%': Array can't be coerced into Fixnum (TypeError)
from euler1.rb:11:in `block (2 levels) in find_sum_for_each_multiple'
from euler1.rb:11:in `downto'
from euler1.rb:11:in `each'
from euler1.rb:11:in `each'
from euler1.rb:11:in `find'
from euler1.rb:11:in `block in find_sum_for_each_multiple'
from euler1.rb:11:in `map'
from euler1.rb:11:in `find_sum_for_each_multiple'
from euler1.rb:18:in `find_sum_of_multiples'
from euler1.rb:32:in `<main>'
我在核心 i7 Windows 7 64 位机器上运行 Ruby 版本 2.0.0p0 (2013-02-24) [x64-mingw32]