Skip to content

Instantly share code, notes, and snippets.

@zverok
Created April 13, 2015 13:15
Show Gist options
  • Save zverok/6785c213fd78430cd423 to your computer and use it in GitHub Desktop.
Save zverok/6785c213fd78430cd423 to your computer and use it in GitHub Desktop.
require 'pp'
class Path < Struct.new(:start_node, :end_node, :color, :type)
def to_s
[start_node, end_node, color, type].join(' ')
end
end
class Test
def initialize
@paths = %Q{A B R C
B E B C
B C B T
C D G T}.split("\n").map{|ln|
Path.new(*ln.split(' '))
}
@adjacency_map = {}
end
attr_reader :adjacency_map
def build_adjacency
@paths.each do |start_path|
@paths.each do |end_path|
next if start_path == end_path
# 3 cases for edge adcency
if (start_path.end_node == end_path.start_node) || (start_path.start_node == end_path.end_node) || (start_path.start_node == end_path.start_node)
if @adjacency_map.has_key?("#{start_path}".to_s)
@adjacency_map[:"#{start_path}".to_s] << end_path
else
value = [end_path]
@adjacency_map[:"#{start_path}".to_s] = value
end
end
end
end
end
end
t = Test.new
t.build_adjacency
pp t.adjacency_map
# output:
# {"A B R C"=>
# [#<struct Path start_node="B", end_node="E", color="B", type="C">,
# #<struct Path start_node="B", end_node="C", color="B", type="T">],
# "B E B C"=>
# [#<struct Path start_node="A", end_node="B", color="R", type="C">,
# #<struct Path start_node="B", end_node="C", color="B", type="T">],
# "B C B T"=>
# [#<struct Path start_node="A", end_node="B", color="R", type="C">,
# #<struct Path start_node="B", end_node="E", color="B", type="C">,
# #<struct Path start_node="C", end_node="D", color="G", type="T">],
# "C D G T"=>[#<struct Path start_node="B", end_node="C", color="B", type="T">]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment