TSort
TSort (위상 정렬)
TSort는 강결합 요소(strongly connected component)를 위한 Tarjan 알고리즘을 사용한 위상 정렬(topological sorting) 을 구현한 모듈이에요. 방향 그래프(directed graph)로 해석할 수 있는 어떤 객체와도 함께 사용할 수 있도록 설계됐어요.
출처: Ruby 3.3 API
본문
TSort는 객체를 그래프로 해석하기 위해 두 메서드를 요구해요. tsort_each_node와 tsort_each_child예요.
tsort_each_node- 그래프의 모든 노드를 순회하는 데 사용해요.tsort_each_child- 주어진 노드의 자식 노드들을 순회하는 데 사용해요.
TSort는 내부적으로 Hash를 사용하므로 노드의 동등성은 eql?과 hash로 정의돼요.
간단한 예제
기존 클래스(여기서는 Hash)에 TSort 모듈을 섞는 예제예요. 해시의 각 키를 그래프의 노드로 취급해서, 필요한 tsort_each_node 메서드를 Hash의 each_key로 별칭(alias)해요. 각 키에 연결된 값은 그 노드의 자식 노드들의 배열이에요.
require 'tsort'
class Hash
include TSort
alias tsort_each_node each_key
def tsort_each_child(node, &block)
fetch(node).each(&block)
end
end
{1=>[2, 3], 2=>[3], 3=>[], 4=>[]}.tsort #=> [3, 2, 1, 4]
{1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}.strongly_connected_components #=> [[4], [2, 3], [1]]
좀 더 현실적인 예제: make 도구
매우 간단한 'make'류 도구를 TSort로 구현할 수 있어요.
require 'tsort'
class Make
def initialize
@dep = {}
@dep.default = []
end
def rule(outputs, inputs=[], &block)
triple = [outputs, inputs, block]
outputs.each {|f| @dep[f] = [triple]}
@dep[triple] = inputs
end
def build(target)
each_strongly_connected_component_from(target) {|ns|
if ns.length != 1
fs = ns.delete_if {|n| Array === n}
raise TSort::Cyclic.new("cyclic dependencies: #{fs.join ', '}")
end
n = ns.first
if Array === n
outputs, inputs, block = n
inputs_time = inputs.map {|f| File.mtime f}.max
begin
outputs_time = outputs.map {|f| File.mtime f}.min
rescue Errno::ENOENT
outputs_time = nil
end
if outputs_time == nil ||
inputs_time != nil && outputs_time <= inputs_time
sleep 1 if inputs_time != nil && inputs_time.to_i == Time.now.to_i
block.call
end
end
}
end
def tsort_each_child(node, &block)
@dep[node].each(&block)
end
include TSort
end
def command(arg)
print arg, "\n"
system arg
end
m = Make.new
m.rule(%w[t1]) { command 'date > t1' }
m.rule(%w[t2]) { command 'date > t2' }
m.rule(%w[t3]) { command 'date > t3' }
m.rule(%w[t4], %w[t1 t3]) { command 'cat t1 t3 > t4' }
m.rule(%w[t5], %w[t4 t2]) { command 'cat t4 t2 > t5' }
m.build('t5')
클래스 메서드 (모듈 함수)
TSort.each_strongly_connected_component(each_node, each_child) { |nodes| ... }
TSort.strongly_connected_components 메서드의 이터레이터 버전이에요. 그래프는 each_node와 each_child로 표현돼요. each_node는 각 노드를 yield하는 call 메서드를 가져야 하고, each_child는 노드 인자를 받아 각 자식 노드를 yield하는 call 메서드를 가져야 해요.
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.each_strongly_connected_component(each_node, each_child) {|scc| p scc }
#=> [4]
# [2]
# [3]
# [1]
TSort.each_strongly_connected_component_from(node, each_child, id_map={}, stack=[]) { |nodes| ... }
그래프의 강결합 요소들을 순회해요. 그래프는 node와 each_child로 표현되고, node는 첫 번째 노드예요. each_child는 노드 인자를 받아 각 자식 노드를 yield하는 call 메서드를 가져야 해요. 반환값은 명시되지 않아요. TSort.each_strongly_connected_component_from는 클래스 메서드라서 TSort를 포함한 그래프를 나타낼 클래스가 필요하지 않아요.
graph = {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}
each_child = lambda {|n, &b| graph[n].each(&b)}
TSort.each_strongly_connected_component_from(1, each_child) {|scc|
p scc
}
#=> [4]
# [2, 3]
# [1]
TSort.strongly_connected_components(each_node, each_child)
강결합 요소들을 노드들의 배열의 배열로 돌려줘요. 배열은 자식에서 부모 순서로 정렬돼요. 각 요소가 하나의 강결합 요소를 나타내요.
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)}
p TSort.strongly_connected_components(each_node, each_child) #=> [[4], [2], [3], [1]]
TSort.tsort(each_node, each_child)
위상 정렬된 노드의 배열을 돌려줘요. 자식에서 부모 순서로 정렬돼요. 즉 첫 요소는 자식이 없고, 마지막 노드는 부모가 없어요. 순환(cycle)이 있으면 TSort::Cyclic이 발생해요.
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)}
p TSort.tsort(each_node, each_child) #=> [4, 2, 3, 1]
TSort.tsort_each(each_node, each_child) { |node| ... }
TSort.tsort 메서드의 이터레이터 버전이에요.
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
인스턴스 메서드
TSort를 include한 클래스는 tsort_each_node와 tsort_each_child를 구현해야 해요. 둘 다 구현하지 않으면 NotImplementedError가 발생해요.
class G
include TSort
def initialize(g)
@g = g
end
def tsort_each_child(n, &b) @g[n].each(&b) end
def tsort_each_node(&b) @g.each_key(&b) end
end
graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
tsort()
위상 정렬된 노드의 배열을 돌려줘요. 순환이 있으면 TSort::Cyclic이 발생해요.
p graph.tsort #=> [4, 2, 3, 1]
tsort_each() { |node| ... }
tsort 메서드의 이터레이터 버전이에요. obj.tsort_each는 obj.tsort.each와 비슷하지만, 순회 중에 obj를 수정하면 예상치 못한 결과가 생길 수 있어요. tsort_each는 nil을 돌려줘요. 순환이 있으면 TSort::Cyclic이 발생해요.
graph.tsort_each {|n| p n }
#=> 4
# 2
# 3
# 1
strongly_connected_components()
강결합 요소들을 노드 배열들의 배열로 돌려줘요.
graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
p graph.strongly_connected_components #=> [[4], [2], [3], [1]]
graph = G.new({1=>[2], 2=>[3, 4], 3=>[2], 4=>[]})
p graph.strongly_connected_components #=> [[4], [2, 3], [1]]
each_strongly_connected_component() { |nodes| ... }
strongly_connected_components 메서드의 이터레이터 버전이에요. obj.each_strongly_connected_component는 obj.strongly_connected_components.each와 비슷하지만, 순회 중 obj를 수정하면 예상치 못한 결과가 생길 수 있어요. each_strongly_connected_component는 nil을 돌려줘요.
graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
graph.each_strongly_connected_component {|scc| p scc }
#=> [4]
# [2]
# [3]
# [1]
each_strongly_connected_component_from(node, id_map={}, stack=[]) { |nodes| ... }
node에서 도달 가능한 부분 그래프(subgraph)의 강결합 요소들을 순회해요. 반환값은 명시되지 않아요. each_strongly_connected_component_from는 tsort_each_node를 호출하지 않아요.
graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
graph.each_strongly_connected_component_from(2) {|scc| p scc }
#=> [4]
# [2]
graph.each_strongly_connected_component_from(4) {|scc| p scc }
#=> [4]
tsort_each_child(node) { |child| ... } · tsort_each_node() { |node| ... }
확장하는 클래스가 구현해야 하는 메서드예요. tsort_each_child는 node의 자식 노드들을 순회하는 데 쓰고, tsort_each_node는 그래프의 모든 노드를 순회하는 데 써요.
참고자료
이 알고리즘의 원천은 Tarjan, "Depth First Search and Linear Graph Algorithms", SIAM Journal on Computing, Vol. 1, No. 2, pp. 146-160, June 1972, 이에요. 그리고 'tsort.rb'는 이름이 어긋난다는 지적이 있어요. 이 라이브러리는 강결합 요소 알고리즘을 쓰는데, 'strongly_connected_components.rb'가 맞지만 너무 길어서 이 이름을 썼다고 해요.