forked from manwar/perlweeklychallenge-club
/
ch-2.pl
executable file
·93 lines (82 loc) · 1.54 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/usr/bin/env perl
use v5.38;
sub isDiagonal($x, $y, $N) {
return (
$N == 1 || $N == 2 || $x == $y || $x + $y == $N - 1
);
}
sub isXMatrix(@matrix) {
my $N = scalar @matrix;
foreach my $y ( 0 .. $#matrix ) {
my @row = @{$matrix[$y]};
foreach my $x ( 0 .. $#row ) {
my $value = $row[$x];
# fail if diagonal values are zero or
# non-diagonal values are non-zero
return 0
unless isDiagonal($x, $y, $N) == ($value != 0);
}
}
return 1;
}
sub formatMatrix($matrix, $indent=17) {
my @output;
foreach my $row (@$matrix) {
my $output_row = q{ } x $indent . " [";
$output_row .= join(', ', map { sprintf "%1d", $_ } @$row) . ']';
push @output, $output_row;
}
return "[\n"
. join(",\n", @output)
. "\n"
. q{ } x $indent . "]";
}
sub solution(@matrix) {
say 'Input: $matrix = ' . formatMatrix(\@matrix);
say 'Output: ' . (isXMatrix(@matrix) ? 'True' : 'False');
}
say "Example 1:";
solution(
[1, 0, 0, 2],
[0, 3, 4, 0],
[0, 5, 6, 0],
[7, 0, 0, 1],
);
say "\nExample 2:";
solution(
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
);
say "\nExample 3:";
solution(
[1, 0, 2],
[0, 3, 0],
[4, 0, 5],
);
say "\nExample 4:";
solution(
[1, 0, 0, 0, 1],
[0, 1, 0, 1, 0],
[0, 0, 1, 0, 0],
[0, 1, 0, 1, 0],
[1, 0, 0, 0, 1],
);
say "\nExample 5:";
solution(
[1, 0, 1, 0, 1],
[0, 1, 0, 1, 0],
[0, 0, 1, 0, 0],
[0, 1, 0, 1, 0],
[1, 0, 0, 0, 1],
);
say "\nExample 6:";
solution(
[1, 1],
[1, 1],
);
say "\nExample 7:";
solution(
[1, 0],
[1, 1],
);