【问题标题】:Convert array with integers which indicate hash depth to hash [closed]将表示散列深度的整数数组转换为散列[关闭]
【发布时间】:2018-08-07 08:46:45
【问题描述】:

我有以下数组:

[{text: "a", depth: 0},
 {text: "b", depth: 1},
 {text: "c", depth: 2},
 {text: "d", depth: 1}]

我要解决的问题是采用扁平数组(上图)并根据每个元素的深度创建嵌套结构。我需要它嵌套的原因是递归地构建一个列表(有序或无序),我无法使用我拥有的数组。

以下内容以某种方式,塑造或形成所需的输出。我尝试创建的嵌套结构的总体思路应该更清晰。

  { 
    text: "a", 
    depth: 0,
    sublevel: [
      {
        text: "a",
        depth: 1,
        sublevel: [
          {
            text: "b",
            depth: 2,
            sublevel: []
          }
        ]
      },
      {
        text: "d",
        depth: 1,
        sublevel: []
      }
    ]
  }

【问题讨论】:

  • 视情况而定;它是这样的已知格式,还是可以按任意顺序排列?如果是任意顺序,你如何确定它们应该嵌套在什么下面?我的意思是,鉴于您的特定输入和输出,这似乎很容易。
  • @DaveNewton 订单很重要。
  • @user3229073 注意depth: 1 是如何出现在预期的解决方案中的两次? ruby 中的哈希不能有重复的键,所以这是不可行的。
  • 请求的输出无效 ruby​​: 子级别 1 上的哈希不能有两个或多个元素共享相同的键(在这种情况下为:text。)也就是说,这个问题没有解决方案,因为它是声明。
  • 现在您的示例输出与输入完全不匹配。

标签: arrays json ruby data-structures ruby-hash


【解决方案1】:

我想通了。

new_structure = []
depth = 0
array.each do |element|
  if element[:depth] == 0
    new_structure << element
  else
    if element[:depth] < depth || element[:depth] == depth
      parent = recursive_method(new_structure[-1], element[:depth] - 1)[:sublevel]
      parent = [] if parent.nil?
      parent << element
    else
      recursive_method(new_structure[-1], element[:depth]).merge!({ sublevel: [element] })
    end
  end
  depth = element[:depth]
end

def recursive_method(structure, depth)
  return structure if structure[:sublevel].nil? || depth == 0
  recursive_method(structure[:sublevel][-1], depth -= 1)
end

结果:

[
  {
    :text => "a",
    :depth => 0,
    :sublevel => [
        {
            :text => "b",
            :depth => 1,
            :sublevel => [
                {
                    :text => "c",
                    :depth => 2
                }
            ]
        }, 
        {
            :text => "d",
            :depth => 1
        }
    ]
  }
]

打开以使其更好。

【讨论】:

    猜你喜欢
    • 2020-12-23
    • 2015-06-12
    • 2016-08-10
    • 2020-06-29
    • 2013-05-16
    • 2018-12-28
    • 2015-07-01
    • 1970-01-01
    • 2016-07-18
    相关资源
    最近更新 更多