in reply to representing a tree

What have you tried so far? Show us some code so we see some effort from you, we can help you if you tell us with which part of the task you have problems with.

If you don't show any effort, it feels like homework, which many of us don't like to answer.

Replies are listed 'Best First'.
Re^2: representing a tree
by baxy77bax (Deacon) on Jul 03, 2008 at 09:37 UTC
    you're right it does sound's like homework but is has passed quite some time since i last attended any real classes. so what i tried so far is through recursion catch the pattern to transform it to the nice tree :
    use strict; open (T, "<", "file.txt")|| die "$!"; open (OUT, ">", "out.txt") || die "$!"; my $t = $ARGV[0];# $t could be 3 not 1 so that i can start from that p +oint my %hash; while (<T>){ m/^(\d+?),(\d+?)\n/g; my ($child, $parent) = ($2,$1); push @{$hash{$child}},$parent; } walk($t); sub walk { my $numb = shift; print OUT "\|->$numb\n"; #my @walk = $numb; for (@{$hash{$numb}}){ #push @walk, #print OUTNOD "\|->>>"; walk($_); print OUTNOD "\|->>"; } #return @walk; }
    there are some relict's in the code but that is because i'm still trying to figure it out.
      push @{$hash{$child}},$parent;

      That doesn't look right. Usually you store a tree the other way round, i.e. for each node you store a list of child nodes. So change that to push @{$hash{$parent}}, $child;, and you'll start to get some results.

      This is how I'd traverse the tree:

      sub other_walk { my ($indent, $item) = @_; print ' ' x (2 * $indent); print $item, "\n"; for (@{$hash{$item}}){ other_walk($indent+1, $_); } } other_walk(0, 1);

      It's not perfect, but I think it goes into the right direction, and you can add your ASCII art eye candy later on ;-)