Module: Trainworks::GraphBuilder

Defined in:
lib/trainworks/graph_builder.rb

Overview

GraphBuilder is responsible to transform tuples (in our case Routes) into a Hash which represents a list of adjacencies between the nodes.

@todo: encapsulate the idea of a Graph inside a class instead of relying on Hash class.

Class Method Summary collapse

Class Method Details

.add_edge(graph, from, to, distance) ⇒ Hash

Adds a new edge to the graph. It checks if the key from (node) is present in the graph and adds to it the to with its distance.

Parameters:

  • graph (Hash)
  • from (Object)
  • to (Object)
  • distance (Object)

Returns:

  • (Hash)

    graph with the new edge



22
23
24
25
26
27
28
29
# File 'lib/trainworks/graph_builder.rb', line 22

def self.add_edge(graph, from, to, distance)
  if graph.key?(from)
    graph[from][to] = distance
  else
    graph[from] = Hash[to, distance]
  end
  graph
end

.build(routes) ⇒ Hash

Parameters:

Returns:

  • (Hash)


9
10
11
12
13
# File 'lib/trainworks/graph_builder.rb', line 9

def self.build(routes)
  routes.reduce({}) do |graph, route|
    add_edge(graph, route.from, route.to, route.distance)
  end
end