in reply to Re: Convert array to tree OR why variable changes arbitrarily
in thread Convert array to tree OR why variable changes arbitrarily

Thank you, this is elegant solution (a little bit complicated for late night but working :)). How did you mean keeping counter for $index? And also, I am aware that this will work only if @arr is "sorted", I will try to improve algorithm and if I lost then I will ask again :) Thank you.
  • Comment on Re^2: Convert array to tree OR why variable changes arbitrarily

Replies are listed 'Best First'.
Re^3: Convert array to tree OR why variable changes arbitrarily
by hdb (Monsignor) on May 31, 2013 at 07:11 UTC

    Basically, you would be counting the $treeElements while iterating over them, so you have the correct $index always at hand. Looks a bit redundant, but I prefer it over grep.

    sub buildTree{ my ($tree, $parNg, $subNg) = @_; my $index = 0; for my $treeElement (@{$tree}){ if (ref $treeElement eq "ARRAY"){ return 1 if &buildTree($treeElement, $parNg, $subNg); } else { if ($treeElement eq $parNg){ splice @{$tree}, $index + 1, 0, $subNg; return 1; } } $index++; } return 0; }