Class: KnapsackSolver::Instance

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

Overview

This class represents an instance of a 0/1 knapsack problem.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(capacity, things) ⇒ Instance

Initializes instance of a 0/1 knapsack problem.



8
9
10
11
# File 'lib/knapsack_solver/instance.rb', line 8

def initialize(capacity, things)
  @weight_capacity = capacity
  @things = things
end

Instance Attribute Details

#thingsObject (readonly)

Returns the value of attribute things.



46
47
48
# File 'lib/knapsack_solver/instance.rb', line 46

def things
  @things
end

#weight_capacityObject (readonly)

Returns the value of attribute weight_capacity.



46
47
48
# File 'lib/knapsack_solver/instance.rb', line 46

def weight_capacity
  @weight_capacity
end

Class Method Details

.parse(line) ⇒ Instance

Creates new instance of a 0/1 knapsack problem.



17
18
19
20
21
22
23
24
25
26
# File 'lib/knapsack_solver/instance.rb', line 17

def self.parse(line)
  thing = Struct.new(:price, :weight, :index)
  # Rozdelit riadok na slova a previest na cisla
  items = split_line(line)
  # Inicializacia premennych
  things = items.drop(1).each_slice(2).with_index.each_with_object([]) do |(s, i), o|
    o << thing.new(s[0], s[1], i)
  end
  Instance.new(items[0], things)
end

.split_line(line) ⇒ Array<Integer>

Splits line that describes an instance of a 0/1 knapsack problem to individual numbers.



33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/knapsack_solver/instance.rb', line 33

def self.split_line(line)
  items = line.split.map! do |i|
    n = Integer(i)
    raise StandardError, 'dataset: instance desctiption contains negative number' if n < 0
    n
  end
  raise StandardError, 'dataset: missing knapsack capacity' if items.empty?
  raise StandardError, 'dataset: missing pairs (price, weight)' if items.size.even?
  items
rescue ArgumentError
  raise StandardError, 'dataset: instance desctiption does not contain only integers'
end