Class: TspRunner::Solution
- Inherits:
-
Object
- Object
- TspRunner::Solution
- Defined in:
- lib/tsp_runner/solution.rb
Instance Attribute Summary collapse
-
#location_hash ⇒ Object
readonly
Returns the value of attribute location_hash.
-
#location_names ⇒ Object
readonly
Returns the value of attribute location_names.
Class Method Summary collapse
Instance Method Summary collapse
- #<<(location_name) ⇒ Object
-
#initialize(location_hash) ⇒ Solution
constructor
A new instance of Solution.
- #total_distance ⇒ Object
- #valid?(initial_location_name = nil) ⇒ Boolean
Constructor Details
#initialize(location_hash) ⇒ Solution
Returns a new instance of Solution.
21 22 23 24 |
# File 'lib/tsp_runner/solution.rb', line 21 def initialize(location_hash) @location_hash = location_hash @location_names = [] end |
Instance Attribute Details
#location_hash ⇒ Object (readonly)
Returns the value of attribute location_hash.
3 4 5 |
# File 'lib/tsp_runner/solution.rb', line 3 def location_hash @location_hash end |
#location_names ⇒ Object (readonly)
Returns the value of attribute location_names.
3 4 5 |
# File 'lib/tsp_runner/solution.rb', line 3 def location_names @location_names end |
Class Method Details
.from_file(filename, location_hash) ⇒ Object
5 6 7 8 9 10 11 |
# File 'lib/tsp_runner/solution.rb', line 5 def self.from_file(filename, location_hash) new(location_hash).tap do |solution| File.open(filename).each do |line| solution << line.chomp end end end |
.from_string(str, location_hash) ⇒ Object
13 14 15 16 17 18 19 |
# File 'lib/tsp_runner/solution.rb', line 13 def self.from_string(str, location_hash) new(location_hash).tap do |solution| str.split("\n").each do |line| solution << line.chomp end end end |
Instance Method Details
#<<(location_name) ⇒ Object
26 27 28 |
# File 'lib/tsp_runner/solution.rb', line 26 def <<(location_name) location_names << location_name end |
#total_distance ⇒ Object
37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/tsp_runner/solution.rb', line 37 def total_distance distance = 0 location_names.each.with_index do |location_name, index| location = location_hash[location_name] next_index = (index + 1) % location_names.length next_location_name = location_names[next_index] next_location = location_hash[next_location_name] distance += location.distance_from(next_location) end distance end |
#valid?(initial_location_name = nil) ⇒ Boolean
30 31 32 33 34 35 |
# File 'lib/tsp_runner/solution.rb', line 30 def valid?(initial_location_name = nil) if initial_location_name return false if initial_location_name != location_names.first end location_hash.location_names.sort == location_names.sort end |