digraph G {
view1_1 -> view1
view1_2 -> view1
a_view1_1_1 -> view1_1
c_view1_and_1_1 -> view1_1
c_view1_and_1_1 -> view1
z_view1_1_2 -> view1_1
}
我怎样才能得到这个结果:
view1
view1_1
a_view1_1_1
c_view1_and_1_1
view1_2
z_view1_1_2
对于某些上下文,需要在开源项目上生成可复制的文件输出:https://github.com/thoughtbot/scenic/pull/191
我开始实现tsort和原始字母排序的混合,例如:
最佳答案
我意识到tsort给我的输出实际上是正确的,即使与我的直觉不一样:
require 'tsort'
tree = {
"view1" => [],
"view1_1" => ["view1"],
"view1_2" => ["view1"],
"a_view1_1_1" => ["view1_1"],
"c_view1_and_1_1" => ["view1_1", "view1"],
"z_view1_1_2" => ["view1_1"],
}
class Hash
include TSort
def tsort_each_node(&block)
keys.sort.each(&block)
end
def tsort_each_child(node, &block)
fetch(node).each { |n| yield(n) }
end
end
tree = Hash[*tree.to_a.shuffle.flatten(1)]
puts tree.tsort
# BONUS: p tree.strongly_connected_components
它给出:
view1
view1_1
a_view1_1_1
c_view1_and_1_1
view1_2
z_view1_1_2
关于ruby - ruby 中按字母顺序的拓扑排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42917771/