Perl Weekly Challenge 140: Multiplication Tables

These are some answers to the Week 140 of the Perl Weekly Challenge organized by Mohammad S. Anwar.

Task 1: Add Binary

This task was covered in the following blog post: https://blogs.perl.org/users/laurent_r/2021/11/perl-weekly-challenge-140-add-binary.html.

Task 2: Multiplication Table

You are given 3 positive integers, $i, $j and $k.

Write a script to print the $kth element in the sorted multiplication table of $i and $j.

Example 1:

Input: $i = 2; $j = 3; $k = 4
Output: 3

Since the multiplication of 2 x 3 is as below:

    1 2 3
    2 4 6

The sorted multiplication table:

    1 2 2 3 4 6

Now the 4th element in the table is "3".

Example 2:

Input: $i = 3; $j = 3; $k = 6
Output: 4

Since the multiplication of 3 x 3 is as below:

    1 2 3
    2 4 6
    3 6 9

The sorted multiplication table:

    1 2 2 3 3 4 6 6 9

Now the 6th element in the table is "4".

Multiplication Table in Raku

We use the built-in infix X cross-product operator to create all combinations from each range, and combine it with the * multiplication operators to obtain all the products of the multiplication table. Then, we simply sort the values obtained and pick the right one (at index $k - 1). In Raku, we can chain all these operations in just one code-line:

use v6;

sub mult-table (UInt $i, UInt $j, UInt $k) {
    say (sort 1..$i X* 1..$j)[$k - 1]
}
for (2, 3, 4), (3, 3, 6) -> $a, $b, $c {
    mult-table $a, $b, $c;
}

This script displays the following output:

raku ./mult-table.raku
3
4

Multiplication Table in Perl

Since we don’t have the cross-product operator in Perl, we will simply use two nested for loops to compute the products and store them in the @products array. Then, we sort the values obtained and pick the right one (at index $k - 1).

use strict;
use warnings;
use feature "say";

sub mult_table {
    my ($c, $d, $k) = @{$_[0]};
    my @products;
    for my $i (1..$c) {
        for my $j (1..$d) {
            push @products, $i * $j;
        }
    }
    say +(sort {$a <=> $b} @products)[$k - 1];

}
for my $test ([2, 3, 4], [3, 3, 6]) {
    mult_table $test;
}

This script displays the following output:

$ perl mult-table.pl
3
4

Wrapping up

The next week Perl Weekly Challenge will start soon. If you want to participate in this challenge, please check https://perlweeklychallenge.org/ and make sure you answer the challenge before 23:59 BST (British summer time) on December 5, 2021. And, please, also spread the word about the Perl Weekly Challenge if you can.

Leave a comment

About laurent_r

user-pic I am the author of the "Think Perl 6" book (O'Reilly, 2017) and I blog about the Perl 5 and Raku programming languages.