blogs.perl.org - 2023-12-04T03:12:11Z
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.
AI生成摘要
本文是Perl Weekly Challenge第245周任务2的答案。任务要求给定一个大于等于0的整数数组,编写一个脚本返回由给定整数任意顺序连接而成的最大数,该数同时也是3的倍数。如果找不到符合条件的数,则返回-1。通过对输入数组进行降序排序,可以得到连接整数的最大组合。本文给出了Raku和Perl两种语言的解决方案。