在此递归函数结束时,数组大小重置为0

时间:2013-08-23 02:07:10

标签: ruby

我的目标是返回一个数组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"

1 个答案:

答案 0 :(得分: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]]