aboutsummaryrefslogtreecommitdiff
path: root/challenge-053/dave-cross/perl/ch-1.pl
blob: c958c67144d72c6811bc4f6a64bba88b1a91e686 (plain)
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
#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

sub print_matrix {
  my ($matrix) = @_;

  for (@$matrix) {
    say '[', join(', ', @$_), ']';
  }
}

sub rotate_matrix {
  my ($matrix, $degrees) = @_;

  die "Must give rotation in degrees\n" unless $degrees;
  die "Must rotate by 90, 180 or 270 degrees\n"
    if $degrees =~ /\D/ or $degrees % 90 or $degrees > 270;

  my $rotated_matrix;

  for (1 .. $degrees / 90) {
    $rotated_matrix = [];
    for my $i (0 .. $#$matrix) {
      for my $j (0 .. $#{$matrix->[$i]}) {
        $rotated_matrix->[$j][$#{$matrix->[$i]} - $i] = $matrix->[$i][$j];
      }
    }
    $matrix = $rotated_matrix;
  }

  return $rotated_matrix;
}

my $input = [
  [1, 2 ,3],
  [4, 5, 6],
  [7, 8, 9],
];
say "Original matrix:";
print_matrix($input);
for (90, 180, 270) {
  say "Rotating by $_ degrees:";
  print_matrix(rotate_matrix($input, $_));
}