Advent Calendar - December 16, 2021

Thursday, Dec 16, 2021| Tags: Perl, Raku

Advent Calendar 2021

| Day 15 | Day 16 | Day 17 |


The gift is presented by Jaldhar H. Vyas. Today he is talking about his solution to “The Weekly Challenge - 108”. This is re-produced for Advent Calendar 2021 from the original post by Jaldhar H. Vyas.



Task #2: Bell Numbers


Write a script to display top 10 Bell Numbers. Please refer to wikipedia page for more information.




Ugh maths again. Not being able to make head nor tail of the referenced wikipedia page, I googled around and found this page. The code below is a Raku translation of the C++ example provided there.


sub bellNumber(Int $n) {
    my @bell;
    @bell[0][0] = 1;
    for 1 .. $n -> $i {
        @bell[$i][0] = @bell[$i - 1][$i - 1];

        for 1 .. $i -> $j {
            @bell[$i][$j] = @bell[$i - 1][$j - 1] + @bell[$i][$j - 1];
        }
    }
    return @bell[$n][0];
}

Full code on GitHub

Basically we are creating what’s known as a Bell Triangle by starting with a known value (1 for a set with 0 elements) and using dynamic programming to calculate succeeding values. The leftmost value in the $nth row of the triangle is the Bell number for $n.

This is the same thing in Perl:


sub bellNumber {
    my ($n) = @_;
    my @bell;
    $bell[0][0] = 1;
    for my $i (1 .. $n) {
        $bell[$i][0] = $bell[$i - 1][$i - 1];

        for my $j (1 .. $i) {
            $bell[$i][$j] = $bell[$i - 1][$j - 1] + $bell[$i][$j - 1];
        }
    }
    return $bell[$n][0];
}

Full code on GitHub

The spec asks for the “top ten” Bell numbers by which I assume the first ten is meant. In case you are curious, they are:


1 1 2 5 15 52 203 877 4140 21147


If you have any suggestion then please do share with us perlweeklychallenge@yahoo.com.

Advent Calendar 2021

SO WHAT DO YOU THINK ?

If you have any suggestions or ideas then please do share with us.

Contact with me