Class: ORTools::KnapsackSolver

Inherits:
Object
  • Object
show all
Defined in:
lib/or_tools/knapsack_solver.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.new(*args) ⇒ Object



3
4
5
6
# File 'lib/or_tools/knapsack_solver.rb', line 3

def self.new(*args)
  args = [:branch_and_bound, "KnapsackExample"] if args.empty?
  super(*args)
end

Instance Method Details

#solve(*args) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/or_tools/knapsack_solver.rb', line 8

def solve(*args)
  return _solve if args.empty?

  values, weights, capacities = *args
  init(values, weights, capacities)
  computed_value = _solve

  packed_items = []
  packed_weights = []
  total_weight = 0
  values.length.times do |i|
    if best_solution_contains?(i)
      packed_items << i
      packed_weights << weights[0][i]
      total_weight += weights[0][i]
    end
  end

  {
    total_value: computed_value,
    total_weight: total_weight,
    packed_items: packed_items,
    packed_weights: packed_weights
  }
end