Skip to content

Instantly share code, notes, and snippets.

@nnabeyang
Created July 31, 2012 01:04
Show Gist options
  • Save nnabeyang/3212414 to your computer and use it in GitHub Desktop.
Save nnabeyang/3212414 to your computer and use it in GitHub Desktop.
Rails::Initializable::Collectionのtsort_eachはこんな感じ
class Node
attr_reader :before, :after, :name
def initialize(name, config)
@name = name
@before = config[:before]
@before = config[:after]
end
def to_s
@name
end
end
require 'tsort'
class TSortArray < Array
include TSort
alias tsort_each_node each
def tsort_each_child(node, &block)
select {|i| i.before == node.name || i.name == node.before}
end
def add(*args)
config = args.last.kind_of?(Hash)? args.pop: {}
self << Node.new(args.first, config)
end
end
a = TSortArray.new
a.add :t7
a.add :t5, :after => :t11
a.add :t3, :after => :t8
a.add :t11, :before => :t7, :after => :t2
a.add :t8, :before => :t7
a.add :t2
a.add :t9
a.add :t10
result = []
a.tsort_each {|i| result << i }
puts result.inspect #=> [t7, t5, t3, t11, t8, t2, t9, t10]
@nnabeyang
Copy link
Author

wikipediaのトポロジカルソートの例と同じDAGになります。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment