TSort

TSort (위상 정렬)

TSortTarjan의 강한 연결 요소(scc, strongly connected components) 알고리즘으로 위상 정렬(topological sort)을 구현한 모듈이에요. 방향 그래프(directed graph)로 해석할 수 있는 어떤 객체에든 섞어 쓸 수 있게 설계됐어요.

객체를 그래프로 해석하려면 두 메서드가 필요해요.

  • tsort_each_node - 그래프의 모든 노드를 순회하는 데 써요.
  • tsort_each_child - 주어진 노드의 자식 노드들을 순회하는 데 써요.

노드의 동등성은 eql?hash로 정의되는데, TSort가 내부적으로 Hash를 쓰기 때문이에요.

출처: Ruby 4.0 API

본문

간단한 예시

다음 예시는 기존 클래스(여기선 Hash)에 TSort 모듈을 섞는 방법을 보여줘요. 해시의 각 키를 그래프의 노드로 취급하고, 필수 메서드인 tsort_each_nodeHash#each_key로 별칭(alias)해요. 각 키에 연결된 값은 그 노드의 자식 노드들의 배열이에요. 그래서 필요한 tsort_each_child는 자식 노드 배열을 가져와 그 배열을 사용자가 준 블록으로 순회하도록 구현해요.

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' 류 도구를 이렇게 구현할 수 있어요.

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')

버그(Bugs)와 참고

  • 'tsort.rb'은 이름이 잘못됐다는 지적이 있어요. 이 라이브러리는 강한 연결 요소를 위해 Tarjan 알고리즘을 쓰는데, 'strongly_connected_components.rb'가 정확하지만 너무 길기 때문이에요.
  • 참고 문헌: Tarjan, "Depth First Search and Linear Graph Algorithms", SIAM Journal on Computing, Vol. 1, No. 2, pp. 146-160, June 1972.

상수 (Constants)

  • VERSION - 버전 문자열.

클래스 메서드 (Public Class Methods)

each_strongly_connected_component(each_node, each_child) { |nodes| ... }

TSort.strongly_connected_components 메서드의 이터레이터 버전이에요.

그래프는 each_nodeeach_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]

each_strongly_connected_component_from(node, each_child, id_map={}, stack=[]) { |nodes| ... }

그래프의 강한 연결 요소를 순회해요. 그래프는 nodeeach_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]

strongly_connected_components(each_node, each_child)

강한 연결 요소를 노드들의 배열의 배열로 돌려줘요. 배열은 자식에서 부모 순으로 정렬돼요. 각 요소가 하나의 강한 연결 요소를 나타내요.

그래프는 each_nodeeach_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(each_node, each_child)

위상 정렬된 노드 배열을 돌려줘요. 배열은 자식에서 부모 순으로 정렬돼요. 즉 첫 요소는 자식이 없고, 마지막 노드는 부모가 없어요.

그래프는 each_nodeeach_child로 표현돼요. 순환(사이클)이 있으면 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]

g = {1=>[2], 2=>[3, 4], 3=>[2], 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) # TSort::Cyclic 발생

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

인스턴스 메서드 (Public Instance Methods)

each_strongly_connected_component() { |nodes| ... }

strongly_connected_components 메서드의 이터레이터 버전이에요. _obj_.each_strongly_connected_component_obj_.strongly_connected_components.each와 비슷하지만, 순회 중에 _obj_를 수정하면 예상 밖의 결과가 나올 수 있어요. nil을 돌려줘요.

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=>[]})
graph.each_strongly_connected_component {|scc| p scc }
#=> [4]
#   [2]
#   [3]
#   [1]

each_strongly_connected_component_from(node, id_map={}, stack=[]) { |nodes| ... }

node에서 도달 가능한 부분 그래프의 강한 연결 요소를 순회해요. 반환 값은 정해져 있지 않아요. tsort_each_node는 호출하지 않아요.

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=>[]})
graph.each_strongly_connected_component_from(2) {|scc| p scc }
#=> [4]
#   [2]

strongly_connected_components()

강한 연결 요소를 노드들의 배열의 배열로 돌려줘요. 배열은 자식에서 부모 순으로 정렬돼요. 각 요소가 하나의 강한 연결 요소를 나타내요.

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=>[]})
p graph.strongly_connected_components #=> [[4], [2], [3], [1]]

tsort()

위상 정렬된 노드 배열을 돌려줘요. 배열은 자식에서 부모 순으로 정렬돼요. 즉 첫 요소는 자식이 없고, 마지막 노드는 부모가 없어요. 순환이 있으면 TSort::Cyclic을 던져요.

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=>[]})
p graph.tsort #=> [4, 2, 3, 1]

graph = G.new({1=>[2], 2=>[3, 4], 3=>[2], 4=>[]})
p graph.tsort # TSort::Cyclic 발생

tsort_each() { |node| ... }

tsort 메서드의 이터레이터 버전이에요. _obj_.tsort_each_obj_.tsort.each와 비슷하지만, 순회 중에 _obj_를 수정하면 예상 밖의 결과가 나올 수 있어요. nil을 돌려줘요. 순환이 있으면 TSort::Cyclic을 던져요.

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=>[]})
graph.tsort_each {|n| p n }
#=> 4
#   2
#   3
#   1

tsort_each_child(node) { |child| ... }

확장하는 클래스에서 반드시 구현해야 해요. _node_의 자식 노드들을 순회하는 데 쓰여요.

tsort_each_node() { |node| ... }

확장하는 클래스에서 반드시 구현해야 해요. 그래프의 모든 노드를 순회하는 데 쓰여요.