Memory and bells
Weekly challenge 108 — 12 April 2021
Week 108: 12 Apr 2021
Write a script to display the first 10 Bell Numbers. Please refer to the Wikipedia page for more information.
Example 1
B[0] = 1 as you can only have one partition of zero
element set {}.
B[1] = 1 as you can only have one partition of one
element set {a}.
B[2] = 2
{a}{b}
{a,b}
B[3] = 5
{a}{b}{c}
{a,b}{c}
{a}{b,c}
{a,c}{b}
{a,b,c}
Eric Bell (1883-1960) was a Scottish mathematician who spent his academic life in the USA. He is remembered especially for his work in number theory, but also for his writing which ranged from scholarly books on number theory through quasi-biographical essays on notable mathematicians to science fiction and poetry.
The Bell Numbers count the number of partitions of a set - exemplified above - but also have applications in probability theory and elsewhere.
The numbers are easily calculated by using a Bell Triangle, as documented in the Wikipedia article referenced in the challenge text, and that's what I did.
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2021-04-12 use utf8; # Week 108 - task 2 - Bell numbers use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; use Encode; bell_numbers(10); sub bell_numbers { my ($limit, @triangle, $j, $k); # initialise $limit = $_[0]; # create Bell's triangle $triangle[0][0] = 1; for $j (1 .. $limit - 1) { $triangle[$j][0] = $triangle[$j - 1][$j - 1]; for $k (1 .. $j) { $triangle[$j][$k] = $triangle[$j - 1][$k - 1] + $triangle[$j][$k - 1]; } } # report say qq[\nInput: $limit]; print qq[Output: ]; print $triangle[$_][0] . ($_ == $limit - 1 ? "\n" : ', ') for 0 .. $limit - 1; }
12 lines of code
I completed this challenge after the closing date
and it has not
been submitted to GitHub
Input: 10 Output: 1, 1, 2, 5, 15, 52, 203, 877, 4140, 21147
Any content of this website which has been created by Peter Campbell Smith is in the public domain