-2

I have the following array:

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

The problem I'm trying to solve is to take a flattened array (above) and create a nested structure based on each element's depth. The reason I need it nested is to build a list (ordered or unordered) recursively which I can't do with the array I have.

The following is in some way, shape, or form the desired output. The general idea for the nested structure I'm trying to create should be clearer.

  { 
    text: "a", 
    depth: 0,
    sublevel: [
      {
        text: "a",
        depth: 1,
        sublevel: [
          {
            text: "b",
            depth: 2,
            sublevel: []
          }
        ]
      },
      {
        text: "d",
        depth: 1,
        sublevel: []
      }
    ]
  }
  • Depends; is it a known format like this, or can they be in arbitrary order? If arbitrary order, how do you determine what they should be nested under? I mean, given your specific input and output it seems pretty easy. – Dave Newton Feb 27 '18 at 16:23
  • @DaveNewton Order is important. – user3229073 Feb 27 '18 at 16:28
  • @mudasobwa haha thanks! – user3229073 Feb 27 '18 at 16:30
  • 1
    @user3229073 Notice how `depth: 1` is present in the expected solutionn twice? Hashes in ruby can't have duplicate keys so that's not feasible. – max pleaner Feb 27 '18 at 16:31
  • @user3229073 What have you tried so far? Beware http://idownvotedbecau.se/noattempt/ and http://idownvotedbecau.se/nocode/. – Dave Newton Feb 27 '18 at 16:31
  • @maxpleaner depth in the resulting hash can be ignored. i will edit the question. – user3229073 Feb 27 '18 at 16:34
  • @DaveNewton i will post my attempt – user3229073 Feb 27 '18 at 16:35
  • 1
    The requested output is not valid ruby: hash on sublevel 1 cannot have two or more elements sharing the same key (`:text` in this case.) That said, this problem has no solution as it is stated. – Aleksei Matiushkin Feb 27 '18 at 16:40
  • @mudasobwa forgive me, i will rethink the structure which is acceptable for my use case – user3229073 Feb 27 '18 at 16:56
  • 1
    Now your example output doesn't match the input, at all. – Sergio Tulentsev Feb 27 '18 at 17:38
  • @SergioTulentsev it's pseudo for the possibility of something along those lines? wondering if it's possible to generate a nested structure given the nested level as an integer. – user3229073 Feb 27 '18 at 17:50
  • @user3229073: everything is possible. Except maybe your example here. I don't see how this output can be derived from that input. – Sergio Tulentsev Feb 27 '18 at 18:21
  • @SergioTulentsev i see, thanks for looking regardless – user3229073 Feb 27 '18 at 18:40
  • What is the code you are having trouble with? What trouble do you have with your code? Do you get an error message? What is the error message? Is the result you are getting not the result you are expecting? What result do you expect and why, what is the result you are getting and how do the two differ? Is the behavior you are observing not the desired behavior? What is the desired behavior and why, what is the observed behavior, and in what way do they differ? Please, provide a [mcve]. – Jörg W Mittag Mar 04 '18 at 06:38
  • Can you provide a *precise* specification of what it is that you want to happen, including any and all rules, exceptions from those rules, corner cases, special cases, boundary cases, and edge cases? Can you provide sample inputs and outputs demonstrating what you expect to happen, both in normal cases, and in all the exceptions, corner cases, special cases, boundary cases, and edge cases? Please, also make sure to provide a [mcve]. – Jörg W Mittag Mar 04 '18 at 06:38
  • "Is it possible to iterate through the array above and create […]" – You do it by writing a program which does that. If you have a problem with your program, carefully read the documentation of all the methods, classes, modules, and libraries you are using, write tests for your programs, trace the execution with pen and paper, single-step it in a debugger, then sleep on it, start again from the beginning, sleep on it again, and *then and only then* narrow your problem down to a concise, focused, simple, short, reproducible [mcve] and ask a specific, focused, narrow question on [so]. – Jörg W Mittag Mar 04 '18 at 06:39
  • Also, please read [this](https://meta.stackoverflow.com/q/270933/2988) to understand why "is it possible" is a poor question, and most likely off-topic for [so], and edit your question accordingly to include the precise problem you are having, the steps you have taken to solve it, and your [mcve]. – Jörg W Mittag Mar 04 '18 at 06:43

1 Answers1

0

I figured it out.

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

Result:

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

Open to make it better.