Skip to content

Instantly share code, notes, and snippets.

/nestedIndex.p6 Secret

Created July 4, 2016 12:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/bbe5e2d798673478bcbbaec51389e76a to your computer and use it in GitHub Desktop.
Save anonymous/bbe5e2d798673478bcbbaec51389e76a to your computer and use it in GitHub Desktop.
my @tree =
<<"Forum 1" 1 20>>,
<<"Forum 1.1" 2 7>>,
<<"Forum1.1.1" 3 4>>,
<<"Forum1.1.2" 5 6>>,
<<"Forum1.2" 8 9>>,
<<"Forum1.3" 10 11>>,
<<"Forum1.4" 12 19>>,
<<"Forum1.4.1" 13 14>>,
<<"Forum1.4.2" 15 18>>,
<<"Forum1.4.2.1" 16 17>>,
;
my $i = 0;
my $d = 0;
sub tree() {
my $node = @tree[$i];
my $left = left($node);
my $right = right($node);
my %result = name => name($node);
while $left + 1 != $right and @tree[++$i]:exists {
my $newRight = right(@tree[$i]);
%result<children>.push: tree();
# only check if we need to break out *AFTER* we added the row
if $newRight + 1 == $right {
last;
}
}
return %result;
};
sub name($a) { $a[0]; }
sub left($a) { $a[1]; }
sub right($a) { $a[2] }
say to-json(tree());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment