in reply to Challenge: Dumping trees.
I am not sure if I add a new approach as I have not studied all posts in this thread in much detail. My code is just a bit shorter and I think a pretty direct approach to the problem.
use strict; use warnings; sub prepare { my( $subtree, $level, $col, $graph ) = @_; my $lcol = 0; if( ref($subtree) ) { $lcol = prepare( $subtree->[0], $level+1, $col, $graph ); # par +se left side of tree, keep top position $lcol and $graph->[$level]->[$_] = '_' for $lcol..$$col-1; # dra +w horizontal line $graph->[$level]->[$$col++] = '/'; $lcol = $$col; # new + root of the tree $graph->[$level]->[$$col++] = '\\'; my $rcol = prepare( $subtree->[1], $level+1, $col, $graph ); # par +se right side of the tree, keep its top position $rcol and $graph->[$level]->[$_] = '_' for $lcol+1..$rcol-1; # dra +w horizontal line } else { $graph->[$level]->[$$col++] = $subtree; # lea +f } return $lcol; # ret +urn column of root } my $root = do { my $r; my @a = ( 'a'..'z', 1..9, 'A'..'Z' ); $r = int( rand $#a ), splice @a, $r, 2, [ @a[ $r, $r+1 ]] while @a + > 1; $a[0]; }; my @graph; my $col = 0; prepare( $root, 0, \$col, \@graph ); for my $row ( @graph ) { print $_ // ' ' for @$row; print "\n"; }
UPDATE: Here is some sample output for a smaller tree:
_____/\_ +_ __________________________/\__ +/\__ ____________________/\________ /\ x + /\ __/\________ _____/\___________ v w + y z __/\ _____/\__ /\__ __/\__ __/\ e /\__ /\__ m /\ _____/\ /\ __/\ d f /\ i /\__ n o /\__ s t u /\ c g h j /\ p /\ a b k l q r
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Challenge: Dumping trees.
by BrowserUk (Patriarch) on Sep 21, 2013 at 21:52 UTC | |
by hdb (Monsignor) on Sep 22, 2013 at 08:35 UTC | |
by BrowserUk (Patriarch) on Sep 22, 2013 at 08:42 UTC |