Class: Mementus::Structure
- Inherits:
-
Object
- Object
- Mementus::Structure
- Defined in:
- lib/mementus/structure.rb
Instance Method Summary collapse
- #add_edge(edge) ⇒ Object
- #add_node(node) ⇒ Object
- #adjacent(id) ⇒ Object
- #directed? ⇒ Boolean
- #each_adjacent(id, &blk) ⇒ Object
- #each_edge(&blk) ⇒ Object
- #each_node(&blk) ⇒ Object
- #edges_count ⇒ Object
- #has_edge?(edge) ⇒ Boolean
- #has_node?(node) ⇒ Boolean
-
#initialize(is_directed = true) ⇒ Structure
constructor
A new instance of Structure.
- #node(id) ⇒ Object
- #nodes ⇒ Object
- #nodes_count ⇒ Object
Constructor Details
#initialize(is_directed = true) ⇒ Structure
3 4 5 6 |
# File 'lib/mementus/structure.rb', line 3 def initialize(is_directed=true) @index = {} @is_directed = is_directed end |
Instance Method Details
#add_edge(edge) ⇒ Object
26 27 28 29 30 31 32 |
# File 'lib/mementus/structure.rb', line 26 def add_edge(edge) add_node(edge.from) unless has_node?(edge.from) add_node(edge.to) unless has_node?(edge.to) @index[edge.from.id].add(edge.to.id) @index[edge.to.id].add(edge.from.id) unless directed? end |
#add_node(node) ⇒ Object
22 23 24 |
# File 'lib/mementus/structure.rb', line 22 def add_node(node) @index[node.id] ||= Set.new end |
#adjacent(id) ⇒ Object
50 51 52 |
# File 'lib/mementus/structure.rb', line 50 def adjacent(id) @index[id].to_a end |
#directed? ⇒ Boolean
18 19 20 |
# File 'lib/mementus/structure.rb', line 18 def directed? @is_directed end |
#each_adjacent(id, &blk) ⇒ Object
58 59 60 |
# File 'lib/mementus/structure.rb', line 58 def each_adjacent(id, &blk) @index[id].each(&blk) end |
#each_edge(&blk) ⇒ Object
62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/mementus/structure.rb', line 62 def each_edge(&blk) if directed? each_node do |from| each_adjacent(from.id) do |to| yield Edge.new(from, to) end end else raise 'Edge traversal unsupported for undirected graphs' end end |
#each_node(&blk) ⇒ Object
54 55 56 |
# File 'lib/mementus/structure.rb', line 54 def each_node(&blk) nodes.each(&blk) end |
#edges_count ⇒ Object
12 13 14 15 16 |
# File 'lib/mementus/structure.rb', line 12 def edges_count c = 0 each_edge { c += 1 } c end |
#has_edge?(edge) ⇒ Boolean
38 39 40 |
# File 'lib/mementus/structure.rb', line 38 def has_edge?(edge) has_node?(edge.from) && @index[edge.from.id].include?(edge.to.id) end |
#has_node?(node) ⇒ Boolean
34 35 36 |
# File 'lib/mementus/structure.rb', line 34 def has_node?(node) @index.key?(node.id) end |
#node(id) ⇒ Object
42 43 44 |
# File 'lib/mementus/structure.rb', line 42 def node(id) NodeProxy.new(id, self) end |
#nodes ⇒ Object
46 47 48 |
# File 'lib/mementus/structure.rb', line 46 def nodes @index.keys.map { |id| NodeProxy.new(id, self) } end |
#nodes_count ⇒ Object
8 9 10 |
# File 'lib/mementus/structure.rb', line 8 def nodes_count @index.size end |