This is in regards to project Euler problem #1. When I run this code line by line in irb, I get the expected answer, but when I run it from a .rb file, it throws error "Array can't be coerced into Fixnum (TypeError)"
Code:
# 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)
Error message:
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>'
I'm running on a core i7 Windows 7 64bit machine with Ruby version 2.0.0p0 (2013-02-24) [x64-mingw32]
commonMultiples
is already an Array
, and in find_sum_for_each_multiple
, it gets converted to an Array
of Arrays
Change this line
sumsOfCommonMultiples = find_sum_for_each_multiple(from, to, commonMultiples)
to
sumsOfCommonMultiples = find_sum_for_each_multiple(from, to, *commonMultiples)