Created
January 7, 2017 16:37
-
-
Save alexandru-calinoiu/0eeab24aeec0ad6a5be31a27012c4a0d to your computer and use it in GitHub Desktop.
A very naive graph implementation in ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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