The weekly challenge 266 - Task 2: X Matrix

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-266/#TASK2
 3 #
 4 # Task 2: X Matrix
 5 # ================
 6 #
 7 # You are given a square matrix, $matrix.
 8 #
 9 # Write a script to find if the given matrix is X Matrix.
10 #
11 ### A square matrix is an X Matrix if all the elements on the main diagonal and
12 ### antidiagonal are non-zero and everything else are zero.
13 #
14 ## Example 1
15 ##
16 ## Input: $matrix = [ [1, 0, 0, 2],
17 ##                    [0, 3, 4, 0],
18 ##                    [0, 5, 6, 0],
19 ##                    [7, 0, 0, 1],
20 ##                  ]
21 ## Output: true
22 #
23 ## Example 2
24 ##
25 ## Input: $matrix = [ [1, 2, 3],
26 ##                    [4, 5, 6],
27 ##                    [7, 8, 9],
28 ##                  ]
29 ## Output: false
30 #
31 ## Example 3
32 ##
33 ## Input: $matrix = [ [1, 0, 2],
34 ##                    [0, 3, 0],
35 ##                    [4, 0, 5],
36 ##                  ]
37 ## Output: true
38 #
39 ############################################################
40 ##
41 ## discussion
42 ##
43 ############################################################
44 #
45 # So we just walk the matrix using an index $i for the rows and another
46 # index $j for the columns. If we're on the diagonals, we check whether
47 # the value is != 0, otherwise we check whether it is == 0.
48 
49 use strict;
50 use warnings;
51 
52 x_matrix( [ [1, 0, 0, 2], [0, 3, 4, 0], [0, 5, 6, 0], [7, 0, 0, 1] ] );
53 x_matrix( [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] );
54 x_matrix( [ [1, 0, 2], [0, 3, 0], [4, 0, 5] ] );
55 
56 sub x_matrix {
57    my $matrix = shift;
58    my $rows = scalar(@$matrix);
59    my $columns = scalar(@{$matrix->[0]});
60    print "Input: [\n";
61    foreach my $row (@$matrix) {
62       print "        [ ", join(", ", @$row), "],\n";
63    }
64    print "]\n";
65    die "Not a square matrix" unless $rows == $columns;
66    my $is_x_matrix = 1;
67    foreach my $i (0..$rows-1) {
68       foreach my $j (0..$columns-1) {
69          if($i==$j or $i == ($columns - 1 - $j)) {
70             $is_x_matrix = 0 unless $matrix->[$i]->[$j] != 0;
71          } else {
72             $is_x_matrix = 0 unless $matrix->[$i]->[$j] == 0;
73          }
74       }
75    }
76    print "Output: ", $is_x_matrix == 0 ? "false" : "true", "\n";
77 }