in reply to compute paths in Pascal's triangle (aka Tartaglia's one)
My suggestion was to modify the recursive formula (function) to return not the sum value, but the paths themselves. Perhaps the more practical alternative is to construct an iterator. I've included both in the code below. Note that the @path have only column numbers. If you need Row-Column coordinates, zip/pairwise them with [0 .. $n] as appropriate.
#! /usr/bin/perl use Algorithm::Combinatorics q(:all); use Data::Dump; use strict; use warnings; push @ARGV, (6, 4); # default (n, k) # recursive formula # sub choose { my ($n, $k) = @_; !$n ? ([$k]) x !$k : map [@$_, $k], choose($n-1, $k), choose($n-1, + $k-1) } dd choose(@ARGV); # iterator version # sub pinball_iter { my ($n, $k) = @_; my $iter = combinations([1 .. $n], $k); sub { my @path = (0); $path[$_]++ for @{ $iter->next() // return }; $path[$_]+=$path[$_-1] for (1 .. $n); return \@path; } } my $it = pinball_iter(@ARGV); while (my $x = $it->()) { dd $x; }
The recursive formula is rather simple, and can be trivially adjusted for Row-Col pairs as well:
sub choose { my ($n, $k) = @_; !$n ? (["$n-$k"]) x !$k : map [@$_, "$n-$k"], choose($n-1, $k), choose($n-1, $k-1) }
|
---|