Sometimes the rule S(n,k) = 0 if k>n is given for completeness
VERY important if you dont realize n elements ... k non-empty subsets
and you just start with
for $n (0..10) {
for $k (0..10) {
print "$n $k '.fs($n,$k)."\n";
}
}
use strict; use warnings;
my $l='k ';
$l.=sprintf "%3d ",0;
for my $k (0..10){
$l.=sprintf " %10s",$k;
}
print $l."\n";
$l=~s/./-/g;
print $l."\n";
for my $n (0..10){
printf "n %3d ",$n;
for my $k (0..10){
printf " %10s",fs($n,$k);
}
print "\n";
}
sub fs {
my $n=shift;
my $k=shift;
if ( $n ==0 && $k == 0 ) {return 1};
if ( $k > $n ) {return 0}; # important
if ( $n > 0 && $k == 0 ) {return 0}
if ( $k == 1 ) {return 1}
if ($n == $k ) {return 1}
my $p1=fs($n-1,$k-1);
my $p2=fs($n-1,$k );
return $p1 + ($k*$p2);
}
And i learned never to name my subroutines
s
use strict; use warnings;
my $l='k ';
$l.=sprintf "%3d ",0;
for my $k (0..10){
$l.=sprintf " %10s",$k;
}
print $l."\n";
$l=~s/./-/g;
print $l."\n";
for my $n (0..10){
printf "n %3d ",$n;
for my $k (0..10){
printf " %10s",s($n,$k);
}
print "\n";
}
sub s {
my $n=shift;
my $k=shift;
if ( $n ==0 && $k == 0 ) {return 1};
if ( $k > $n ) {return 0}; # important
if ( $n > 0 && $k == 0 ) {return 0}
if ( $k == 1 ) {return 1}
if ($n == $k ) {return 1}
my $p1=s($n-1,$k-1);
my $p2=s($n-1,$k );
return $p1 + ($k*$p2);
}
output
Global symbol "$p2" requires explicit package name at buk-2.pl line 30
+.
syntax error at buk-2.pl line 31, near "return"
(Might be a runaway multi-line ;; string starting on line 29)
Global symbol "$p1" requires explicit package name at buk-2.pl line 31
+.
Global symbol "$p2" requires explicit package name at buk-2.pl line 31
+.
Missing right curly or square bracket at buk-2.pl line 32, at end of l
+ine
syntax error at buk-2.pl line 32, at EOF
Execution of buk-2.pl aborted due to compilation errors.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
|
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.