Skip to content

Commit

Permalink
Graph#degree_of(<Node>) method added.
Browse files Browse the repository at this point in the history
  • Loading branch information
bfontaine committed Oct 22, 2012
1 parent 6a4b406 commit 6155353
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 5 deletions.
37 changes: 32 additions & 5 deletions lib/graph.rb
Expand Up @@ -248,17 +248,17 @@ def -(other)
Graph.new(nodes, edges)
end

# @see Graph#-
def not(other)
self - other
end

# Return true if the Graph is directed.
# @see Graph.attrs
def directed?()
self.attrs[:directed]
end

# @see Graph#-
def not(other)
self - other
end

# Clone the current graph. All nodes and edges are also cloned. A new Graph
# is returned.
def clone()
Expand Down Expand Up @@ -301,6 +301,33 @@ def write(filename, opts=nil)

end

# Return the degree of the node n in the current graph, i.e. the number
# of edges which are connected to this node. Note that this is useful
# only for a undirected graph, for a directed one, you should use
# Graph#in_degree_of and/or Graph#out_degree_of.
#
# Edges must have the 'node1' and 'node2' attributes, which must contain
# the 'label' attributes of nodes.
#
# @param n [Node,String] A node or a label of one
def degree_of(n)
label = n.is_a?(Node) \
? (n['label'] || n[:label]).to_s \
: n.is_a?(String) ? n : nil

raise TypeError.new("#{n.inspect} must be a Node or String object.") if label.nil?

degree = 0

self.edges.each do |e|
degree += 1 if (e['node1'] || e[:node1]).to_s == label
degree += 1 if (e['node2'] || e[:node2]).to_s == label
end

degree
end


# return the provided set of graphs, from which every node/edge label which
# is not in all graphs has been removed. So every returned graph has same
# node/edge labels than each other
Expand Down
11 changes: 11 additions & 0 deletions tests/node_tests.rb
Expand Up @@ -51,4 +51,15 @@ def test_node_attrs
assert_equal(nil, @@alice['fooo'])
end

def test_node_degree_by_label
assert_equal(2, @@sample_graph.degree_of('Alice'))
assert_equal(2, @@sample_graph.degree_of('Oscar'))
assert_equal(2, @@sample_graph.degree_of('Bob'))
assert_equal(0, @@sample_graph.degree_of('not found'))
end

def test_node_degree_by_object
assert_equal(2, @@sample_graph.degree_of(@@alice))
end

end

0 comments on commit 6155353

Please sign in to comment.