Peter’s blog ✴ Week 115 ✴ 31 May 2021

THE WEEKLY CHALLENGE
Circles and multiples

The Perl Camel

Task 2

Largest multiple

You are given $N, a list of positive single digit integers (0-9). Write a script to find the largest multiple of 2 that can be formed from the list.

Examples


Example 1
Input: @N = (1, 0, 2, 6)
Output: 6210

Example 2
Input: @N = (1, 4, 2, 8)
Output: 8412

Example 3
Input: @N = (4, 1, 7, 6)
Output: 7614

Analysis

The answer to this is:

  • Reverse sort the list
  • Find the last occurrence of an even digit $s, which will be the smallest even digit in the list
  • Concatenate
    1. all the digits preceding the last occurrence of $s
    2. all the digits following that $s
    3. $s

Conveniently that can be done with a single regex.

I am sorry that the 'Try it' feature is currently working very slowly or not at all owing to some issue with my web hosting provider.

Try it 

Try running the script with any input:



example: 3, 1, 4, 1, 5, 9

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 2021-05-31
use utf8;     # Week 115 - task 2 - Largest multiple
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';
use Encode;

largest_multiple(1, 2, 3, 4, 5);
largest_multiple(1, 0, 2, 6);
largest_multiple(1, 4, 2, 8);
largest_multiple(4, 1, 7, 6);
largest_multiple(1, 3, 5, 7);
largest_multiple(4, 8, 6, 2);

my @x;
push @x, int(rand(10)) for 1 .. 20;
largest_multiple(@x);

sub largest_multiple {
    
    my ($numbers);
    
    # initialise
    say qq[\nInput:  (] . join(', ', @_) . ')';
    
    # concatenate digits in descending order
    $numbers = join('', reverse sort {$a <=> $b} @_);
    
    # find smallest multiple of 2 and move it to the end
    if ($numbers =~ m|^([0-9]*)([02468])([0-9]*)|) {
        say qq[Output: $1$3$2];
    } else {        
        say qq[Output: no multiple of 2 in input];
    }
}

8 lines of code
Completed after the closing date and not submitted to GitHub

Output from script


Input:  (1, 2, 3, 4, 5)
Output: 54312

Input:  (1, 0, 2, 6)
Output: 6210

Input:  (1, 4, 2, 8)
Output: 8412

Input:  (4, 1, 7, 6)
Output: 7614

Input:  (1, 3, 5, 7)
Output: no multiple of 2 in input

Input:  (4, 8, 6, 2)
Output: 8642

Input:  (7, 9, 0, 3, 4, 9, 7, 4, 6, 7, 8, 1, 5, 0, 7, 1,
   3, 8, 8, 6)
Output: 99888777766544331100

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain