이는 프로젝트 오일러 문제 # 1과 관련됩니다. 이 코드를 irb에서 한 줄씩 실행하면 예상되는 대답을 얻을 수 있지만 .rb 파일에서 실행하면 "ArrayNumber (TypeError)로 배열을 강제 변환 할 수 없습니다."Ruby - Array에서 블록 내에서 블록 사용과 관련된 오류를 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 윈도우 7 64 비트 시스템에서 실행 해요 2.0.0p0 (2013년 2월 24일) [64-mingw32]
에
Array
Arrays
의 변경이 라인변환됩니다 투표 했니? 이것은 나에게 합법적 인 질문처럼 보입니다. 만약 인터프리터에서 같은 코드를 한 줄씩 실행하고 아무런 에러도 얻을 수 없지만, 스크립트에서 코드를 실행할 때 에러가 발생한다면, 적어도 저에게 함축 할 것입니다. 내 논리는 맞지만, 실종 된 언어 구현에 대한 구체적인 내용이 있습니다. 나는 약간의 주위에 Google을했지만, 나는이 오류와 관련이 있다고 생각되는 것을 많이 찾지 못했다. 통역사의 결함 일 수 있습니까? – josiah