Working with a directed graph using RGL in Ruby

I implemented a directed graph in Ruby using RGL, just having the difficulty in determining how for a given node to find only nodes with incoming connections and nodes with outgoing connections. Perhaps I missed something simple.

+3
source share
3 answers

I ran into this problem. Using the inverse method may work, although it may not be the most elegant approach:

require 'rgl/adjacency'
require 'rgl/bidirectional'

class RGL::DirectedAdjacencyGraph
    def in_degree(v)
    rdg = self.reverse
    rdg.adjacent_vertices(v).size
  end

  def out_degree(v)
    self.adjacent_vertices(v).size
  end
end

dg=RGL::DirectedAdjacencyGraph[1,2 ,2,3 ,2,4, 4,5, 6,4, 1,6]

p dg.in_degree(2)
#=> 2
p dg.out_degree(2)
#=> 1

p dg.in_degree(1)
#=> 0
p dg.out_degree(3)
#=> 0

The longer answer is that it has not yet been implemented.

, , RGL:: Bidirectional , each_in_neighbor. , - ( ):

require 'rgl/adjacency'
require 'rgl/bidirectional'

class RGL::DirectedAdjacencyGraph
  include RGL::BidirectionalGraph
end

dg=RGL::DirectedAdjacencyGraph[1,2 ,2,3 ,2,4, 4,5, 6,4, 1,6]

dg.vertices
#=> [5, 6, 1, 2, 3, 4]

p dg.adjacent_vertices(2)
#=> [3, 4]

p dg.each_in_neighbor(2)
#=>  NotImplementedError :(
#=> Should be:  [1]

, , , .

: , node. , , , - node .

+3

RGL:: DirectedAdjacencyGraph . , , RGL:: BidirectionalGraph, . , RGL:: BidirectionalGraph # each_in_neighbor .

, in-neighbors , DirectedAdjacencyGraph, . :

# Iterator providing access to the in-edges (for directed graphs) or incident
# edges (for undirected graphs) of vertex _v_. For both directed and
# undirected graphs, the target of an out-edge is required to be vertex _v_
# and the source is required to be a vertex that is adjacent to _v_.
def each_in_neighbor (v, &block)
  in_neighbors = (@vertice_dict_for_in_neighbors[v] or
                  raise NoVertexError, "No vertex #{v}.")
  in_neighbors.each(&block)
end

, .

+2

, Directed Edges:


[RW]
[RW]

? , .

0

Source: https://habr.com/ru/post/1730960/


All Articles