aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authordrbaggy <js5@sanger.ac.uk>2021-04-16 10:04:54 +0100
committerdrbaggy <js5@sanger.ac.uk>2021-04-16 10:04:54 +0100
commitaa1430d0a2213c98716cc17dc96e2b17db1b767d (patch)
tree1baaa2ca7ef85300bf6372fc4deb9760e830c082
parent632bbcb73eb161176ef331234890d36ea1571e96 (diff)
downloadperlweeklychallenge-club-aa1430d0a2213c98716cc17dc96e2b17db1b767d.tar.gz
perlweeklychallenge-club-aa1430d0a2213c98716cc17dc96e2b17db1b767d.tar.bz2
perlweeklychallenge-club-aa1430d0a2213c98716cc17dc96e2b17db1b767d.zip
added some docs
-rw-r--r--challenge-108/james-smith/perl/ch-2.pl43
1 files changed, 38 insertions, 5 deletions
diff --git a/challenge-108/james-smith/perl/ch-2.pl b/challenge-108/james-smith/perl/ch-2.pl
index 524cde283d..9e6d8006f9 100644
--- a/challenge-108/james-smith/perl/ch-2.pl
+++ b/challenge-108/james-smith/perl/ch-2.pl
@@ -14,14 +14,47 @@ is( "@{ bell_numbers(20) }", $ANSWER_20 );
done_testing();
+## Bell numbers can be computed by using a bell triangle.
+## The bell numbers are the last cell of each row of the table.
+##
+## To get one row from the next.
+## * We copy the previous "bell number" the last cell in
+## the previous row.
+## * Each other element of the row is computed by adding the number
+## to the left of it in this row and the element about (and to the
+## left of it)
+##
+## The solution...
+##
+## * We will use 2 arrays to represent the previous row and
+## the current row of the table. @a & @b;
+## We initialise the first row to just contain the number 1 #1
+##
+## * And at each iteration we remember this last element. #2
+##
+## * When we have enough elements in our results array we #3
+## return. We don't need to do last and then return outside
+## the loop as we can just return from the subroutine from
+## inside the loop!
+##
+## * In each iteration we initialise the row to contain the
+## previous last value... #1
+## and then loop through all the elements in the previous #4
+## array accumulating the total - the ability to get the
+## value of the last element of the array with [-1] is
+## very useful perl feature here...
+##
+## * Finally we copy the new row into the previous row and #5
+## continue around the loop....
+
sub bell_numbers {
my $N = shift;
- my @res = my @a = 1;
+ my @res = my @a = 1; #1
while(1) {
- push @res, my @b = $a[-1];
- return \@res if @res >= $N;
- push @b, $b[-1] + $_ foreach @a;
- @a = @b;
+ push @res, my @b = $a[-1]; #2
+ return \@res if @res >= $N; #3
+ push @b, $b[-1] + $_ foreach @a; #4
+ @a = @b; #5
}
}