1

我的目标是返回一个数组bin,其中包含一个数组元素的组合,这些元素的总和将达到某个最大值。

我无法弄清楚为什么bin重置为空。请帮我解决这个问题。

def session_bin(arr, max) 
  array = arr.sort
  bin = []
  bin_value = max
  start = 0
  sum = array[start]
  p array
  array.each_with_index do |l,i|
    p "----before SUM-----#{sum}"

    if sum <= bin_value 
      bin << l
    end   

    if i < array.size-1
      i += 1
    end

    sum  +=  array[i]

    p "bin = #{bin}" 

    while sum > bin_value and i < array.size  do
      sum  -=  array[i]
    end

    return bin if bin.inject(:+) == bin_value

    break if bin.inject(:+) == bin_value
    p "----after SUM-----#{sum}"
  end

  p "---------------------------------------"

  array.delete_at(start)

  p "SUM--------#{sum}"

  if sum < bin_value
    bin.clear
    sum = 0
    session_bin(array, max)
  end 

  p "size = #{bin.size}"
  p bin if !bin.empty?
end


my_instance.session_bin([5, 30, 30, 30, 30, 30, 30, 30, 45, 45, 45, 45, 45, 45, 60, 60, 60, 60, 60], 180)

这是我看到的输出(部分)

"----before SUM-----30" 
"bin = [30]"
"----after SUM-----60"
"----before SUM-----60"
"bin = [30, 30]"
"----after SUM-----90"
"----before SUM-----90"
"bin = [30, 30, 30]"
"----after SUM-----120"
"----before SUM-----120"
"bin = [30, 30, 30, 30]"
"----after SUM-----150"
"----before SUM-----150"
"bin = [30, 30, 30, 30, 30]"
"----after SUM-----180"
"----before SUM-----180"
"bin = [30, 30, 30, 30, 30, 30]"
"size = 0"
4

1 回答 1

2

不是递归的,但是...

def session_bin(arr, max)
  1.upto(arr.size).map { |i| arr.combination(i).to_a }.flatten(1).select { |a| a.inject(:+) == max }.uniq
end

p session_bin [5, 30, 30, 30, 30, 30, 30, 30, 45, 45, 45, 45, 45, 45, 60, 60, 60, 60, 60], 180

#> [[60, 60, 60], [30, 30, 60, 60], [30, 45, 45, 60], [45, 45, 45, 45], [30, 30, 30, 30, 60], [30, 30, 30, 45, 45], [30, 30, 30, 30, 30, 30]]
于 2013-08-23T04:54:41.410 回答