/
ch-2.pl
98 lines (87 loc) · 2.1 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
94
95
96
97
98
use strict;
use warnings;
sub is_reduced_row_echelon {
my ($matrix_ref) = @_;
my @matrix = @{ $matrix_ref->[0] }; # Adjusting matrix access
my $last_leading = -1;
my $zero_row_encountered = 0;
for my $row_index ( 0 .. $#matrix ) {
my $row = $matrix[$row_index];
my $leading = -1;
for my $i ( 0 .. $#$row ) {
my $element = $row->[$i];
if ( $element != 0 ) {
if ( $element == 1 ) {
$leading = $i;
last;
}
else {
return 0;
}
}
}
if ( $leading == -1 ) {
$zero_row_encountered = 1;
next;
}
if ($zero_row_encountered) {
return 0;
}
if ( $leading <= $last_leading ) {
return 0;
}
for my $r_index ( 0 .. $#matrix ) {
next if $r_index == $row_index;
if ( $matrix[$r_index][$leading] != 0 ) {
return 0;
}
}
$last_leading = $leading;
}
return 1;
}
# Test cases
use Test::More;
is( is_reduced_row_echelon( [ [ [ 1, 1, 0 ], [ 0, 1, 0 ], [ 0, 0, 0 ] ] ] ),
0, "Test 1" );
is(
is_reduced_row_echelon(
[
[
[ 0, 1, -2, 0, 1 ],
[ 0, 0, 0, 1, 3 ],
[ 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0 ]
]
]
),
1, "Test 2"
);
is(
is_reduced_row_echelon(
[ [ [ 1, 0, 0, 4 ], [ 0, 1, 0, 7 ], [ 0, 0, 1, -1 ] ] ]
),
1, "Test 3"
);
is(
is_reduced_row_echelon(
[
[
[ 0, 1, -2, 0, 1 ],
[ 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 1, 3 ],
[ 0, 0, 0, 0, 0 ]
]
]
),
0, "Test 4"
);
is( is_reduced_row_echelon( [ [ [ 0, 1, 0 ], [ 1, 0, 0 ], [ 0, 0, 0 ] ] ] ),
0, "Test 5" );
is(
is_reduced_row_echelon(
[ [ [ 4, 0, 0, 0 ], [ 0, 1, 0, 7 ], [ 0, 0, 1, -1 ] ] ]
),
0, "Test 6"
);
done_testing();