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