我有散列(排序),像这样的数组:
testArray = [{price: 540, volume: 12},
{price: 590, volume: 18},
{price: 630, volume: 50}]
现在我想计算平均值达到一定总量。 比方说,有人想购买40件,他希望它最便宜的方式。 这将意味着(540 * 12 + 590 * 18 + 630 * 50)/ 40钱单位的平均价格。
我的第一次尝试以下操作:
testArray.each do |priceHash|
@priceArray << priceHash.fetch(:price)
@volumeArray << priceHash.fetch(:volume)
end
def calculateMiddlePrice(priceArray, volumeArray, totalAmount)
result = 0
# Here some crazy wild magic happens
(0...volumeArray.count).inject(0) do |r, i|
if (volumeArray[0..i].inject(:+)) < totalAmount
r += volumeArray[i]*priceArray[i]
elsif volumeArray[0..i-1].inject(:+) < totalAmount && volumeArray[0..i].inject(:+) >= totalAmount
theRest = volumeArray[i] - (volumeArray[0..i].inject(:+) - totalAmount)
r += theRest * priceArray[i]
elsif volumeArray[0] > totalAmount
r = totalAmount * priceArray[0]
end
result = r
end
result
end
现在我也不知道为什么它的工作原理,但它确实。 然而,在我眼里这简直不可理喻代码。
我的第二个想法是把我的testArray达到总量时。 该代码看起来更好
testAmount = 31
def returnIndexForSlice(array, amount)
sum = 0
array.each_index do |index|
p sum += array[index][:volume]
if sum >= amount
return index+1
end
end
end
testArray.slice(0,returnIndexForSlice(testArray, testAmount))
不过,这只是不觉得正确的,“rubyish”如果你能这么说。 我检查数组类几乎每一个方法,打得四处bsearch,但我想不出解决我的问题的一个非常优雅的方式。
什么是穿越我的脑海里是类似的东西:
amountToCheck = 31
array.some_method.with_index {|sum, index| return index if sum >= amountToCheck}
但是,有没有这样的方法或任何其他方式?