/
ch-1.pl
78 lines (58 loc) · 1.57 KB
/
ch-1.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
#!perl
use strict;
use warnings FATAL => qw(all);
=prompt
Write a script to rotate the following matrix by given 90/180/270 degrees clockwise.
[ 1, 2, 3 ]
[ 4, 5, 6 ]
[ 7, 8, 9 ]
For example, if you rotate by 90 degrees then expected result should be like below
[ 7, 4, 1 ]
[ 8, 5, 2 ]
[ 9, 6, 3 ]
=cut
sub rotate
{
my ($aref, $angle) = @_;
my $rotated;
for my $row_idx ( 0 .. $#$aref )
{
for my $col_idx ( 0 .. $#{$aref->[$row_idx]} )
{
if ( 90 == $angle )
{
$rotated->[$col_idx][$#$aref - $row_idx] =
$aref->[$row_idx][$col_idx];
}
elsif ( 180 == $angle )
{
$rotated->[$#$aref - $row_idx][$#{$aref->[$row_idx]} - $col_idx] =
$aref->[$row_idx][$col_idx];
}
elsif ( 270 == $angle )
{
$rotated->[$#{$aref->[$row_idx]} - $col_idx][$row_idx] = $aref->[$row_idx][$col_idx];
}
else
{
die "Can only rotate a matrix by 90/180/270 degrees clockwise!$/";
}
}
}
return $rotated;
}
sub print_matrix
{
my $aref = $_[0];
for my $row ( @$aref )
{
print '[ ', join(', ', @$row), ' ]', $/;
}
print $/;
}
my @matrix = ([ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]);
my @rotated = map { rotate(\@matrix, $_) } (90, 180, 270);
print_matrix(\@matrix);
print_matrix($_) for @rotated;