The weekly challenge 248 - Task 2: Submatrix Sum

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-248/#TASK2
 3 #
 4 # Task 2: Submatrix Sum
 5 # =====================
 6 #
 7 # You are given a NxM matrix A of integers.
 8 #
 9 # Write a script to construct a (N-1)x(M-1) matrix B having elements that are
10 # the sum over the 2x2 submatrices of A,
11 #
12 # b[i,k] = a[i,k] + a[i,k+1] + a[i+1,k] + a[i+1,k+1]
13 #
14 # 
15 ## Example 1
16 ##
17 ## Input: $a = [
18 ##               [1,  2,  3,  4],
19 ##               [5,  6,  7,  8],
20 ##               [9, 10, 11, 12]
21 ##             ]
22 ##
23 ## Output: $b = [
24 ##                [14, 18, 22],
25 ##                [30, 34, 38]
26 ##              ]
27 #
28 ## Example 2
29 ##
30 ## Input: $a = [
31 ##               [1, 0, 0, 0],
32 ##               [0, 1, 0, 0],
33 ##               [0, 0, 1, 0],
34 ##               [0, 0, 0, 1]
35 ##             ]
36 ##
37 ## Output: $b = [
38 ##                [2, 1, 0],
39 ##                [1, 2, 1],
40 ##                [0, 1, 2]
41 ##              ]
42 #
43 ############################################################
44 ##
45 ## discussion
46 ##
47 ############################################################
48 #
49 # Just some index arithmetic
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 }