我试图将数组中的每个元素乘以接下来的12个元素:
array.each do |n|
a = array.index(n)
b = a + 12
product = 1
array[a..b].each { |i| product *= i }
highest = product if product > highest
end
当数组中出现多个相同整数时遇到问题:
[1, 2, 3, 7, 5, 4, 7] # this is not the actual array
当第二个7
在我的区块中运行时,array.index(n)
成为3
(第一个7
的索引),当我希望它为{{1}时(我正在使用的特定6
的索引)。我很确定这可以通过给出数组中的每个元素一个唯一的'id'来解决,但我不确定如何做到这一点。
我的问题是,如何为数组中的每个元素赋予唯一的ID? 7
方法不是我想要的。
答案 0 :(得分:2)
你可以稍微简化你的代码
highest = array.map.with_index do |item, i|
array[i, 13].inject(:*)
end.max
# printing it console
puts highest
或使用array.max_by
使用明确的i
计数器
答案 1 :(得分:1)
索引是uniq id。请改用Enumerable#each_with_index
:
array.each_with_index do |n, a|
#...
end
答案 2 :(得分:1)
Ruby有each_cons
method defined on Enumerable。each_cons
是each_consecutive的缩写。
array.each_cons(13).max_by{|slice| slice.inject(:*)}
为了提高效率,请考虑确定前十三个数字的乘积;然后通过数组将乘积乘以下一个数字并除以前一个数字,同时跟踪最大乘积。