簡體   English   中英

使用字符串數組的樹節點

[英]Tree Nodes using array of strings

我正在嘗試使用字符串數組構建一個具有根,子節點和孫子節點的樹。 我有這樣的數組

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/"

編輯:我想以這樣的方式輸出,通過使用根節點我可以確定子孫。

我確信有更好的方法可以做到這一點,但如果這可以幫助你

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: {}
roots, children, grandchildren =
array.group_by{|s| s.count("/")}.values_at(2, 3, 4)

這就是我要做的事情:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM