/
ch-2.pl
57 lines (50 loc) · 1.28 KB
/
ch-2.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/env perl
use v5.38;
use Array::Utils qw( intersect );
use List::Util qw( min max );
sub maxCols(@matrix) {
my @rotated; # rotate cols to rows
foreach my $row ( @matrix ) {
foreach my $k ( 0 .. $#{$row} ) {
my $v = $row->[$k];
push @{$rotated[$k]}, $v;
}
}
# return the max of the now rows!
return map { max( @$_ ) } @rotated;
}
sub luckyNumber(@matrix) {
my @minRows = map { min( @$_ ) } @matrix;
my @maxCols = maxCols(@matrix);
# intersect() returns an array, so get the first element
return (intersect( @minRows, @maxCols ))[0] // -1;
}
sub formatMatrix(@matrix) {
my $indent = 17;
my @output;
foreach my $row ( @matrix ) {
my $output_row = q{ } x $indent . " [";
$output_row .= join(', ', map { sprintf "%2d", $_ } @$row);
push @output, $output_row;
}
return "[\n"
. join(",\n", @output)
. "\n"
. q{ } x $indent . "]";
}
sub solution(@matrix) {
say 'Input: $matrix = ' . formatMatrix(@matrix);
my $lucky = luckyNumber(@matrix);
say "Output: $lucky";
}
say "Example 1:";
solution([ 3, 7, 8],
[ 9, 11, 13],
[15, 16, 17]);
say "\nExample 2:";
solution([ 1, 10, 4, 2],
[ 9, 3, 8, 7],
[15, 16, 17, 12]);
say "\nExample 3:";
solution([7, 8],
[1, 2]);