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 に答える