-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtsort.rb
75 lines (62 loc) · 1.18 KB
/
tsort.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/env ruby
# topological sort with detection
# http://en.wikipedia.org/wiki/Topological_sorting
def visit(graph, node, deps, visited, &block)
v = visited[node]
if v == :just
return true
elsif v == :once
return false
else
visited[node] = :just
deps.each do |dep|
if visit(graph, dep, graph[dep], visited, &block)
return true
end
end
visited[node] = :once
block.call(node)
end
end
def tsort(graph, &block)
visited = {}
graph.each_pair do |node, deps|
return true if visit(graph, node, deps, visited, &block)
end
return false
end
test_data = {
:graph1 => {
'a' => ['b'],
'b' => ['c'],
'c' => [],
},
:graph2 => {
'a' => [],
'b' => [],
'c' => ['a', 'b'],
},
:graph3 => {
'a' => ['a'],
},
:graph4 => {
'a' => ['b'],
'b' => ['c'],
'c' => ['a'],
},
:graph5 => {
'a' => ['b', 'c'],
'b' => ['a', 'c'],
'c' => ['a', 'b'],
},
}
test_data.each_pair do |name, graph|
puts "#{name.to_s}"
print " in : "; p graph
print " out : "
cyclic = tsort(graph) do |node|
print "#{node} -> "
end
print "\n"
puts cyclic ? " cyclic" : " asyclic"
end