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"