Method: TSort.tsort_each
- Defined in:
- lib/tsort.rb
.tsort_each(each_node, each_child) ⇒ Object
The iterator version of the TSort.tsort method.
The graph is represented by each_node and each_child. each_node should have call method which yields for each node in the graph. each_child should have call method which takes a node argument and yields for each child node.
g = {1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]}
each_node = lambda {|&b| g.each_key(&b) }
each_child = lambda {|n, &b| g[n].each(&b) }
TSort.tsort_each(each_node, each_child) {|n| p n }
#=> 4
# 2
# 3
# 1
226 227 228 229 230 231 232 233 234 235 236 |
# File 'lib/tsort.rb', line 226 def self.tsort_each(each_node, each_child) # :yields: node return to_enum(__method__, each_node, each_child) unless block_given? each_strongly_connected_component(each_node, each_child) {|component| if component.size == 1 yield component.first else raise Cyclic.new("topological sort failed: #{component.inspect}") end } end |