0

我正在尝试使用字符串数组构建具有根节点、子节点和孙节点的树。我有一个这样的数组

array = [
  "/capacitor/",
  "/capacitor/non_polarized/",
  "/capacitor/non_polarized/ceramic/",
  "/capacitor/polarized/",
  "/capacitor/polarized/al/",
  "/connector/",
  "/diode/",
  "/diode/normal/",
  "/optical/",
  "/optical/emmision/diode/",
  "/optical/emmision/laser/",
  "/optical/detector/",
  "/optical/detector/diode/"
]

我想取这个数组并确定相应的节点。那些像

"/capacitor/", "/connector/", "/diode/"

是根节点。那些像

"/capacitor/non_polarized/", "/capacitor/polarized/", "/optical/detector/"

是子节点,最后是像

"/optical/detector/diode/", "/optical/emmision/laser/"

是孙节点。有两个/和文本之间的字符串是根节点,三个/是子节点,四个/是孙节点。

想象一下我有电容器作为我的根节点,现在我会有root_node = "capacitor" child_node = "/capacitor/non_polarized/","/capacitor/polarized/" and grandchild_node = "/capacitor/non_polarized/ceramic/", "/capacitor/polarized/al/"

编辑:我希望以这样一种方式输出,即通过使用根节点,我可以确定子孙。

4

3 回答 3

1

我相信有更好的方法可以做到这一点,但如果这可以帮助你

tree = array.inject({}) do |h, string|
  values = string.split('/').reject(&:empty?)
  top = values.shift
  h[top] ||= {}
  values.inject(h[top]) do |sub_h, value|
    sub_h[value] ||= {}
  end
  h
end

y tree
#--- 
#capacitor: 
#  non_polarized: 
#    ceramic: {}
#
#  polarized: 
#    al: {}
#
#connector: {}
#
#diode: 
#  normal: {}
#
#optical: 
#  emmision: 
#    diode: {}
#
#    laser: {}
#
#  detector: 
#    diode: {}
于 2013-07-05T09:56:03.143 回答
1
roots, children, grandchildren =
array.group_by{|s| s.count("/")}.values_at(2, 3, 4)
于 2013-07-05T10:28:11.010 回答
0

这是我要做的:

class TreeNode
  attr_accessor :name, :children

  def initialize(name, children_strings)
    @name = name
    @children = []
    @children << TreeNode.new(children_strings.shift, children_strings) if !children_strings.nil? and children_strings.count > 0
    self
  end

  def to_hash
    { name => children.map(&:to_hash) }
  end

  def self.process_node(root, strings_array)
    next_node = root.children.detect { |n| n.name == strings_array.first }
    if !next_node.nil?
      strings_array.shift
      process_node(next_node, strings_array)
    else
      root.children << TreeNode.new(strings_array.shift, strings_array)
    end
  end

  def self.process_array(array)
    root = TreeNode.new('root', nil)
    array.each do |string| 
      strings_array = string.split('/')
      strings_array.shift
      TreeNode.process_node(root, strings_array)
    end
    root
  end
end

root = TreeNode.process_array(array)
于 2013-07-05T12:36:36.390 回答