The weekly challenge 266 - Task 2: X Matrix
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 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 }