Skip to content

Instantly share code, notes, and snippets.

@phamonyut
Last active August 29, 2015 14:21
Show Gist options
  • Save phamonyut/d9257f1878e38666b510 to your computer and use it in GitHub Desktop.
Save phamonyut/d9257f1878e38666b510 to your computer and use it in GitHub Desktop.
# train_service.rb
# Graph data structure is contain from, to and distance
class Graph
attr_accessor :from, :to, :distance
def initialize(from, to, distance)
@from = from
@to = to
@distance = distance.to_i
end
end
# Train Service
class TrainService
attr_reader :rules
def initialize(rules)
@rules = TrainService.convert_to_graph rules
end
# calculate distance
def distance(routes)
sum_distance = 0
routes = routes.split('-')
routes.each_with_index do |route, index|
break if index == routes.length - 1
rule = @rules.select { |rule| rule.from == route && rule.to == routes[index + 1] }
fail 'NO SUCH ROUTE' if rule.empty?
sum_distance += rule.first.distance
end
sum_distance
end
# convert input to graph object
def self.convert_to_graph(rules)
rules.split(', ').map { |rule| Graph.new(rule[0], rule[1], rule[2]) }
end
end
# example input
rules = 'AB5, BC4, CD8, DC8, DE6, AD5, CE2, EB3, AE7'
routes = 'A-E-B-C-D'
# run
train_service = TrainService.new rules
begin
distance = train_service.distance routes
puts distance
rescue StandardError => e
puts e.message
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment