You are given a list of positive integers (
0-9
), single digit.Write a script to find the largest multiple of
2
that can be formed from the list.
Input: @N = (1, 0, 2, 6) Output: 6210 Input: @N = (1, 4, 2, 8) Output: 8412 Input: @N = (4, 1, 7, 6) Output: 7614
This is pretty simple. To get the highest possible number, we just list the digits, highest to lowest. To get the highest possible even number, we take the smallest even digit, place it last, and list the rest of the digits, highest to lowest.
We will bother sorting the digits — in fact, we won't even store all the digits. Instead, we will just count them.
We will have the list of digits in $_
. First, we count them:
my @DIGITS = (0 .. 9);
my @EVENS = grep {$_ % 2 == 0} @DIGITS;
my @digits = (0) x @DIGITS;
$digits [$_] ++ for do {local $" = ""; /[@DIGITS]/g}
We then find the smallest even digit, and remove it from the count. (If there is not even digit, we won't output anything):
my ($last) = grep {$digits [$_]} @EVENS;
next unless defined $last;
$digits [$last] --;
Now, print the digits highest to lowest, with the smallest even digit last:
print join "" => map {$_ x $digits [$_]} reverse @DIGITS;
say $last;
Find the full program on GitHub.
We also have implementations in AWK, Bash, C, Lua, Node.js, Python and Ruby which all work the same as the Perl solution.