Perl Weekly Challenge 245: Largest of Three

These are some answers to the Week 245, Task 2, of the Perl Weekly Challenge organized by Mohammad S. Anwar.

Task 2: Largest of Three

You are given an array of integers >= 0.

Write a script to return the largest number formed by concatenating some of the given integers in any order which is also a multiple of 3. Return -1 if none found.

Example 1

Input: @ints = (8, 1, 9)
Output: 981

981 % 3 == 0

Example 2

Input: @ints = (8, 6, 7, 1, 0)
Output: 8760

Example 3

Input: @ints = (1)
Output: -1

We will use the Raku built-in combinations routine to generate the various possibilities. Note that if any number is a multiple of 3, then, any permutation of its digits is also a multiple of 3. So sorting the input array in descending order will provide us with combinations leading to the largest concatenations of integers.

Largest of Three in Raku

Using the above comments, we arrive at the following Raku solution:

sub largest-three (@ints) {
    my $max = -1;
    my @sorted = @ints.sort.reverse;
    for @sorted.combinations: 1..@ints.elems -> @seq {
        my $val = [~] @seq;
        next unless $val %% 3;
        $max = $val if $val > $max;
    }
    return $max > 0 ?? $max !! -1;
}

my @tests = <8 1 9>, <8 1 9 3>, <8 6 7 1 0>, (0,);
for @tests -> @test {
    printf "%-10s => ", "@test[]";
    say largest-three @test;
}

This program displays the following output:

$ raku ./largest-three.raku    
8 1 9      => 981
8 1 9 3    => 9831
8 6 7 1 0  => 8760
0          => -1

Largest of Three in Perl

Not enough time this week for a solution to this challenge in Perl. Sorry.

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 10, 2023. 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.