これは、プロジェクト オイラーの問題 #1 に関するものです。このコードを irb で 1 行ずつ実行すると、期待どおりの答えが得られますが、.rb ファイルから実行すると、「Array can't be coerced into 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>'
Ruby バージョン 2.0.0p0 (2013-02-24) [x64-mingw32] を搭載したコア i7 Windows 7 64 ビット マシンで実行しています。