Class: Djikstra::Cli
- Inherits:
-
Object
- Object
- Djikstra::Cli
- Defined in:
- lib/djikstra/cli.rb
Instance Method Summary collapse
-
#initialize(*args) ⇒ Cli
constructor
A new instance of Cli.
- #parse ⇒ Object
- #run ⇒ Object
- #usage ⇒ Object
Constructor Details
#initialize(*args) ⇒ Cli
Returns a new instance of Cli.
3 4 5 6 7 |
# File 'lib/djikstra/cli.rb', line 3 def initialize(*args) @file = args[0] @start = args[1].to_s.upcase @stop = args[2].to_s.upcase end |
Instance Method Details
#parse ⇒ Object
26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/djikstra/cli.rb', line 26 def parse edges = [] open(@file) do |f| f.readlines.each_with_index do |line,idx| items = line.split /\[(\w+),(\w+),(\d+)\]/ # only care about the center matches edges.push [items[1],items[2],items[3],idx+1] end end edges end |
#run ⇒ Object
39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/djikstra/cli.rb', line 39 def run return usage unless @file && @start && @stop graph = Graph.new(parse) path = graph.shortest_path_between(@start,@stop) dist = graph.shortest_path_distance puts "Shortest path is [#{path.join(',')}] with a total cost of #{dist}" rescue ParseError, GraphError => e puts e.to_s exit 1 end |
#usage ⇒ Object
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/djikstra/cli.rb', line 9 def usage puts "#{$0} <file> <start> <end>" puts " file - a DAG graph file" puts " start - the name of starting node" puts " end - the name of the ending node" puts puts " DAG graph file contains lines (between two nodes) and weights in the following format" puts " [A,B,1]" puts " [B,C,3]" puts puts "Example:" puts " $ #{$0} graph.txt A C" puts " Shortest path is [A,B,C] with total cost 4" exit 1 end |