The weekly challenge 248 - Task 2: Submatrix Sum
1 #!/usr/bin/env perl
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 submatrix_sum( [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ] );
52 submatrix_sum( [ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1] ] );
53
54 sub submatrix_sum {
55 my $matrix = shift;
56 print "Input: [\n";
57 foreach my $array (@$matrix) {
58 print " [" . join(",", @$array) . "],\n";
59 }
60 print " ]\n";
61 my $l = scalar(@$matrix);
62 my $m = scalar(@{$matrix->[0]});
63 my $resultmatrix = [];
64 foreach my $i (0..$l-2) {
65 foreach my $k (0..$m-2) {
66 $resultmatrix->[$i]->[$k] = $matrix->[$i]->[$k] + $matrix->[$i]->[$k+1] + $matrix->[$i+1]->[$k] + $matrix->[$i+1]->[$k+1];
67 }
68 }
69 print "Output: [\n";
70 foreach my $array (@$resultmatrix) {
71 print " [" . join(",", @$array) . "],\n";
72 }
73 print " ]\n";
74 }