Weekly Challenge 338
Each week Mohammad S. Anwar sends out The Weekly Challenge, a chance for all of us to come up with solutions to two weekly tasks. My solutions are written in Python first, and then converted to Perl. It's a great way for us all to practice some coding.
Task 1: Highest Row
Task
You are given a m x n
matrix.
Write a script to find the highest row sum in the given matrix.
My solution
For input from the command line, I take a JSON-formatted string and turn it into a list of list of integers (arrays in Perl).
This is a one liner in Python, using the sum
function to calculate the sum of each row, and the max
function to return the highest (maximum) sum.
def highest_row(matrix: list[list[int]]) -> int:
return max(sum(row) for row in matrix)
While Perl does not have a built-in max
and sum
function, they are provided by the List::Util module. Therefore the solution is similar.
use List::Util qw(max sum);
sub main ($matrix) {
my $max = max( map { sum @$_ } @$matrix );
say $max;
}
Examples
$ ./ch-1.py "[[4, 4, 4, 4], [10, 0, 0, 0], [2, 2, 2, 9]]"
16
$ ./ch-1.py "[[1, 5], [7, 3], [3, 5]]"
10
$ ./ch-1.py "[[1, 2, 3], [3, 2, 1]]"
6
$ ./ch-1.py "[[2, 8, 7], [7, 1, 3], [1, 9, 5]]"
17
$ ./ch-1.py "[[10, 20, 30], [5, 5, 5], [0, 100, 0], [25, 25, 25]]"
100
Task 2: Max Distance
Task
You are given two integer arrays, @arr1
and @arr2
.
Write a script to find the maximum difference between any pair of values from both arrays.
My solution
For input from the command line, I take two strings and separate them on non-digit characters to turn them into two lists (arrays in Perl).
There are at least two possible ways to solve this, each with pros and cons.
I could extract the minimum and maximum values of each array, and compare the minimum of one list with the maximum of the other. The advantage of this is we only scan each list once, and do three additional calculations. The con is that it is significantly more code than the other solution.
The solution that I did write is a one liner in Python, by using double list comprehension and the abs
and max
function.
def max_distance(arr1: list[int], arr2: list[int]) -> int:
return max(abs(a - b) for a in arr1 for b in arr2)
Perl does not have list comprehension (it does have map
, but double mapping is asking for a world of pain). Therefore I use two foreach
loops to get the same result.
sub main (@arrays) {
my @arr1 = split /\D+/, $arrays[0];
my @arr2 = split /\D+/, $arrays[1];
my $max = 0;
for my $a1 (@arr1) {
for my $a2 (@arr2) {
my $dist = abs( $a1 - $a2 );
$max = $dist if $dist > $max;
}
}
say $max;
}
Examples
$ ./ch-2.py "4 5 7" "9 1 3 4"
6
$ ./ch-2.py "2 3 5 4" "3 2 5 5 8 7"
6
$ ./ch-2.py "2 1 11 3" "2 5 10 2"
9
$ ./ch-2.py "1 2 3" "3 2 1"
2
$ ./ch-2.py "1 0 2 3" "5 0"
5
Top comments (0)