Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Since you don't show what format the data is after you parse, I'm going to guess :) Here's how I would store the parsed data in ruby objects (using new-style hash key syntax for clarity):</p> <pre><code>[ {yes: 2, no: 3}, {yes: 4}, {yes: 4}, {yes: -1} ] </code></pre> <p>Then, tree-traversal can be done recursively. As long as your arrays aren't several thousands of elements long, this will work fine.</p> <pre><code>def tree(object_number, list) if object_number == list.size [[object_number]] else list[object_number-1].values.map { |obj_num| tree(obj_num,list) }.inject{|a,b| a+b}.map{|l| [object_number] + l} end end </code></pre> <p>Now you call the function:</p> <pre><code>tree(1,data) =&gt; [[1, 2, 4], [1, 3, 4]] data = [ {yes: 2, no: 3}, {yes: 4, no:5}, {yes:5, no:4}, {yes:5}, {yes: -1} ] tree(1,data) =&gt; [[1, 2, 4, 5], [1, 2, 5], [1, 3, 5], [1, 3, 4, 5]] </code></pre> <p><em><strong>How it works:</em></strong> The easiest way to build this list is backwards, since we only know the number of paths once we have gotten to the end of all of them. So this code follows the references all the way to the end, and when it gets to the last object, it returns it as a single-element two dimensional array.</p> <pre><code>tree(5,list) =&gt; [[5]] </code></pre> <p>at each level of recursion, it takes the results of it's recursion call (returned as a list of lists) and prepends it's own object number to each of the interior lists. So, following back up the tree:</p> <pre><code>tree(4,list) # prepends 4 to tree(5) =&gt; [[4,5]] tree(3,list) # prepends 3 to tree(4) and tree(5) =&gt; [[3,4,5],[3,5]] tree(2,list) # prepends 2 to tree(4) and tree(5) =&gt; [[2,4,5],[2,5]] tree(1,list) # prepends 1 to tree(2) and tree(3) =&gt; [[1, 2, 4, 5], [1, 2, 5], [1, 3, 5], [1, 3, 4, 5]] </code></pre> <p>If the lists might be long enough to overflow your stack, it is always possible to do this without recursion. Recursion is just the simplest way for this particular problem.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload