总和数组值达到一定的总量(Sum array values up to a certain tota

2019-10-30 03:03发布

我有散列(排序),像这样的数组:

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}

但是,有没有这样的方法或任何其他方式?

Answer 1:

鉴于你的价格散列的数组:

prices = [  {price: 540, volume: 12},
            {price: 590, volume: 18},
            {price: 630, volume: 50}]

您可以在2个步骤计算你的结果。

def calc_price(prices, amount)
  order = prices.flat_map{|item| [item[:price]] * item[:volume] } #step 1      
  order.first(amount).reduce(:+)/amount #step 2
end

第1步:创建一个有各个项目(如果价格不排序,你必须添加一个数组sort_by条款)。 换言之,扩大了价格到含有12个540的,18度590的等数字数组这使用Ruby的阵列重复方法: [n] * 3 = [n, n, n]

步骤2:平均前n个元素

结果:

calc_price(prices, 40)
=> 585


文章来源: Sum array values up to a certain total amount
标签: ruby arrays sum