我想编写一个函数,将带有路径信息的扁平数组转换为该数组的树形表示。
目标是将以下形式的数组转换为树形结构:
将其转化为以下格式之一:
目标是将以下形式的数组转换为树形结构:
[
{ :name => "a", :path => [ 'a' ] },
{ :name => "b", :path => [ 'a', 'b' ] },
{ :name => "c", :path => [ 'a', 'b', 'c' ] },
{ :name => "d", :path => [ 'a', 'd' ] },
{ :name => "e", :path => [ 'e' ] }
]
将其转化为以下格式之一:
[{:node=>{:name=>"a", :path=>["a"]},
:children=>
[{:node=>{:name=>"b", :path=>["a", "b"]},
:children=>
[{:node=>{:name=>"c", :path=>["a", "b", "c"]}, :children=>[]}]},
{:node=>{:name=>"d", :path=>["a", "d"]}, :children=>[]}]},
{:node=>{:name=>"e", :path=>["e"]}, :children=>[]}]
我用以下代码得到了最接近的结果:
class Tree
def initialize
@root = { :node => nil, :children => [ ] }
end
def from_array( array )
array.inject(self) { |tree, node| tree.add(node) }
@root[:children]
end
def add(node)
recursive_add(@root, node[:path].dup, node)
self
end
private
def recursive_add(parent, path, node)
if(path.empty?)
parent[:node] = node
return
end
current_path = path.shift
children_nodes = parent[:children].find { |child| child[:node][:path].last == current_path }
unless children_nodes
children_nodes = { :node => nil, :children => [ ] }
parent[:children].push children_nodes
end
recursive_add(children_nodes, path, node)
end
end
flat = [
{ :name => "a", :path => [ 'a' ] },
{ :name => "b", :path => [ 'a', 'b' ] },
{ :name => "c", :path => [ 'a', 'b', 'c' ] },
{ :name => "d", :path => [ 'a', 'd' ] },
{ :name => "e", :path => [ 'e' ] }
]
require 'pp'
pp Tree.new.from_array( flat )
但这种方法非常冗长,我感觉对于非常大的数据集可能不太有效。
在Ruby中,最干净、最有效的方法是什么?