Discipulus:
Looks like there are already a bunch of good solutions to your problem. But I did it anyway for a bit of diversion, so rather than throwing it away, I'll add it to the list:
#!env perl
#
# ex_tartaglias_triangle.pl
#
# Find all paths any node R-C to the root (0-0), only moving upwards:
#
# 0-0
# 1-0 1-1
# 2-0 2-1 2-2
# 3-0 3-1 3-2 3-3
# 4-0 4-1 4-2 4-3 4-4
# 5-0 5-1 5-2 5-3 5-4 5-5
#
use strict;
use warnings;
for my $r (0 .. 5) {
for my $c (0 .. $r) {
my $N = aNode->new($r, $c);
print "\n*** ", $N->to_str, ", # paths to root: ", $N->cnt_pat
+hs, " ***\n\n";
for my $rp ($N->paths) {
print "\t", join(" -> ", map { $_->to_str } reverse @$rp),
+ "\n";
}
print "\n";
}
}
{
package aNode;
sub new {
my ($cl, $r, $c) = @_;
my $t = bless { r=>$r, c=>$c, root=>$r==0 }, $cl;
return $t;
}
sub is_root { return $_[0]->{root}; }
sub moves {
my $self = shift;
my @rv;
push @rv, aNode->new($self->{r}-1, $self->{c}-1) if $self->{r}
+ and $self->{c};
push @rv, aNode->new($self->{r}-1, $self->{c}) if $self->{c}
+ < $self->{r};
return @rv;
}
sub paths {
my $self = shift;
return [$self] if $self->is_root;
my @rv;
for my $m ($self->moves) {
push @rv, [ $self, @$_ ] for $m->paths;
}
return @rv;
}
sub cnt_paths {
my $self = shift;
return 1 if $self->is_root;
my $rv = 0;
for my $n ($self->moves) {
$rv += $n->cnt_paths;
}
return $rv;
}
sub to_str {
my $self = shift;
return "$self->{r}-$self->{c}";
}
}
Update: Rather than building the paths from the root to the specified node, I took advantage of the fact that there are only 1 or 2 moves upwards from any node. Then I recursively gathered the paths upwards. I then reversed the path before printing so it looks like a path from the root to the node, instead of the node to the root.
...roboticus
When your only tool is a hammer, all problems look like your thumb.