Class: KnapsackSolver::HeuristicPriceToWeight
- Inherits:
-
Object
- Object
- KnapsackSolver::HeuristicPriceToWeight
- Defined in:
- lib/knapsack_solver/solving_methods/heuristic_price_weight.rb
Overview
This class implements methods for solving 0/1 knapsack problem using simple heuristic by price to weight ratio. Things with the best price to weight ratio are selected first.
Instance Method Summary collapse
-
#initialize(instance) ⇒ HeuristicPriceToWeight
constructor
Initializes instance of 0/1 knapsack problem solver using simple heuristic by price to weight ratio.
-
#run ⇒ Hash
Solve the instance of 0/1 knapsack problem.
Constructor Details
#initialize(instance) ⇒ HeuristicPriceToWeight
Initializes instance of 0/1 knapsack problem solver using simple heuristic by price to weight ratio.
10 11 12 13 14 15 16 |
# File 'lib/knapsack_solver/solving_methods/heuristic_price_weight.rb', line 10 def initialize(instance) @instance = instance @config = Array.new(instance.things.size) { 0 } @sorted_things = instance.things.sort do |a, b| (b.price.to_f / b.weight) <=> (a.price.to_f / a.weight) end end |
Instance Method Details
#run ⇒ Hash
Solve the instance of 0/1 knapsack problem.
21 22 23 24 |
# File 'lib/knapsack_solver/solving_methods/heuristic_price_weight.rb', line 21 def run solve { price: @best_price, config: @best_config } end |