perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 338 - Task 1: Highest Row

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-338/#TASK1
 3 #
 4 # Task 1: Highest Row
 5 # ===================
 6 #
 7 # You are given a m x n matrix.
 8 #
 9 # Write a script to find the highest row sum in the given matrix.
10 #
11 ## Example 1
12 ##
13 ## Input: @matrix = ([4,  4, 4, 4],
14 ##                   [10, 0, 0, 0],
15 ##                   [2,  2, 2, 9])
16 ## Output: 16
17 ##
18 ## Row 1: 4  + 4 + 4 + 4 => 16
19 ## Row 2: 10 + 0 + 0 + 0 => 10
20 ## Row 3: 2  + 2 + 2 + 9 => 15
21 #
22 #
23 ## Example 2
24 ##
25 ## Input: @matrix = ([1, 5],
26 ##                   [7, 3],
27 ##                   [3, 5])
28 ## Output: 10
29 #
30 #
31 ## Example 3
32 ##
33 ## Input: @matrix = ([1, 2, 3],
34 ##                   [3, 2, 1])
35 ## Output: 6
36 #
37 #
38 ## Example 4
39 ##
40 ## Input: @matrix = ([2, 8, 7],
41 ##                   [7, 1, 3],
42 ##                   [1, 9, 5])
43 ## Output: 17
44 #
45 #
46 ## Example 5
47 ##
48 ## Input: @matrix = ([10, 20,  30],
49 ##                   [5,  5,   5],
50 ##                   [0,  100, 0],
51 ##                   [25, 25,  25])
52 ## Output: 100
53 #
54 ############################################################
55 ##
56 ## discussion
57 ##
58 ############################################################
59 #
60 # This one is very simple with a little help of List::Util:
61 # We just create all the sums using sum() and calculate the
62 # maximum of those using max(). map() helps to put everything
63 # into a single line.
64 
65 use v5.36;
66 use List::Util qw(max sum);
67 
68 highest_row([4,  4, 4, 4], [10, 0, 0, 0], [2,  2, 2, 9]);
69 highest_row([1, 5], [7, 3], [3, 5]);
70 highest_row([1, 2, 3], [3, 2, 1]);
71 highest_row([2, 8, 7], [7, 1, 3], [1, 9, 5]);
72 highest_row([10, 20,  30], [5,  5,   5], [0,  100, 0], [25, 25,  25]);
73 
74 sub highest_row( @matrix ) {
75     say "Input: \@matrix = (";
76     foreach my $line (@matrix) {
77         say "    [" . join(", ", @$line) . "],";
78     }
79     say " )";
80     say "Output: " . max( map { sum(@{$_}) } @matrix);
81 }