Skip to content

Instantly share code, notes, and snippets.

@alexandru-calinoiu
Created January 7, 2017 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexandru-calinoiu/0eeab24aeec0ad6a5be31a27012c4a0d to your computer and use it in GitHub Desktop.
Save alexandru-calinoiu/0eeab24aeec0ad6a5be31a27012c4a0d to your computer and use it in GitHub Desktop.
A very naive graph implementation in ruby
require 'pp'
class Graph
def initialize(graph = {})
@hash = graph.freeze
end
def add_vertex(node)
Graph.new(@hash.merge(Hash[node, { edges: {}.freeze }]).freeze)
end
def remove_vertex(node)
Graph.new(@hash.reject { |key, _| key == node })
end
def add_edge(start_node, end_node)
return unless @hash.key?(start_node) && @hash.key?(end_node)
Graph.new(@hash.merge(Hash[
start_node, { edges: @hash[start_node][:edges].merge(Hash[end_node, true]).freeze },
end_node, { edges: @hash[end_node][:edges].merge(Hash[start_node, true]).freeze }
]))
end
def remove_edge(start_node, end_node)
return unless @hash.key?(start_node) && @hash.key?(end_node)
Graph.new(@hash.merge(Hash[
start_node, { edges: Hash[@hash[start_node][:edges].reject { |key, _| key == end_node }].freeze },
end_node, { edges: Hash[@hash[end_node][:edges].reject { |key, _| key == start_node }].freeze }
]))
end
end
dev_book = Graph.new
.add_vertex('James Gosling')
.add_vertex('Guido Rossum')
.add_vertex('Linus Torvalds')
.add_vertex('Michael Olorunnisola')
.add_edge('James Gosling', 'Guido Rossum')
.add_edge('Linus Torvalds', 'Michael Olorunnisola')
.remove_edge('Linus Torvalds', 'Michael Olorunnisola')
.remove_vertex('Linus Torvalds')
pp dev_book
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment