S
soup_or_power
I'm trying to list all the paths in a tree. The tree is specified by
the following hash:
my %tree=(
"a1" => ["a2", "a6", "a9"],
"a2" => ["a3", "a4", "a5"],
"a6" => ["a7", "a8"],
"a9" => ["a10", "a11"],
"a10" => ["a12", "a13"]
);
I want to extract the paths as follows:
a1 - a2 - a3
a1 - a2 - a4
a1 - a2 - a5
a1 - a6 - a7
a1 - a6 - a8
a1 - a9 - a10 - a12
a1 - a9 - a10 - a13
a1 - a9 - a11
Can anyone help me out? I am posting my code just in case anyone can
improve it. Many thanks!
use Data:umper;
my %tree=(
"a1" => ["a2", "a6", "a9"],
"a2" => ["a3", "a4", "a5"],
"a6" => ["a7", "a8"],
"a9" => ["a10", "a11"],
"a10" => ["a12", "a13"]
);
$depth{"a10"}=2;
$depth{"a11"}=2;
$depth{"a12"}=3;
$depth{"a13"}=3;
&Data:umper:umper(\$tree);
my $path=();
my $each=();
my $root="";
my $iter=0, $root;
sub recur() {
my ($top, %tree)=@_;
if ($iter == 0) {
$root=$top;
$iter=1;
}
if ( exists $tree{$top}) {
} else {
push @$path, @each;
print "this is each:\n";
foreach my $h (@each) {
print "$h\n";
}
my $x=pop @each;
print "popping last $x";
return;
}
print "entering for top=$top";
foreach my $k ($tree{$top}) {
if ($depth{$top} != @each) {
@each=();
}
@each=mypush($root, @each);
@each=mypush($top, @each);
print "\npushed top=$top\n";
foreach my $h (@each) {
print "my $h\n";
}
foreach (@$k) {
print "pushing $_ for parent $top\n";
@each=mypush($_, @each);
recur($_, %tree);
}
}
}
sub mypush() {
my($v, @a)=@_;
my $flg=0;
foreach (@a) {
if ($v eq $_) {
$flg=1;
}
}
if ($flg == 1) {
} else {
push @a, $v;
}
return @a;
}
the following hash:
my %tree=(
"a1" => ["a2", "a6", "a9"],
"a2" => ["a3", "a4", "a5"],
"a6" => ["a7", "a8"],
"a9" => ["a10", "a11"],
"a10" => ["a12", "a13"]
);
I want to extract the paths as follows:
a1 - a2 - a3
a1 - a2 - a4
a1 - a2 - a5
a1 - a6 - a7
a1 - a6 - a8
a1 - a9 - a10 - a12
a1 - a9 - a10 - a13
a1 - a9 - a11
Can anyone help me out? I am posting my code just in case anyone can
improve it. Many thanks!
use Data:umper;
my %tree=(
"a1" => ["a2", "a6", "a9"],
"a2" => ["a3", "a4", "a5"],
"a6" => ["a7", "a8"],
"a9" => ["a10", "a11"],
"a10" => ["a12", "a13"]
);
$depth{"a10"}=2;
$depth{"a11"}=2;
$depth{"a12"}=3;
$depth{"a13"}=3;
&Data:umper:umper(\$tree);
my $path=();
my $each=();
my $root="";
my $iter=0, $root;
sub recur() {
my ($top, %tree)=@_;
if ($iter == 0) {
$root=$top;
$iter=1;
}
if ( exists $tree{$top}) {
} else {
push @$path, @each;
print "this is each:\n";
foreach my $h (@each) {
print "$h\n";
}
my $x=pop @each;
print "popping last $x";
return;
}
print "entering for top=$top";
foreach my $k ($tree{$top}) {
if ($depth{$top} != @each) {
@each=();
}
@each=mypush($root, @each);
@each=mypush($top, @each);
print "\npushed top=$top\n";
foreach my $h (@each) {
print "my $h\n";
}
foreach (@$k) {
print "pushing $_ for parent $top\n";
@each=mypush($_, @each);
recur($_, %tree);
}
}
}
sub mypush() {
my($v, @a)=@_;
my $flg=0;
foreach (@a) {
if ($v eq $_) {
$flg=1;
}
}
if ($flg == 1) {
} else {
push @a, $v;
}
return @a;
}