exercism-perl5

Repository for my Perl 5 Exercism exercises
git clone git://git.samirparikh.com/exercism-perl5
Log | Files | Refs | README

Minesweeper.pm (1789B) - raw


      1 package Minesweeper;
      2 use strict;
      3 use warnings;
      4 use Exporter qw<import>;
      5 our @EXPORT_OK = qw<annotate>;
      6 
      7 sub annotate {
      8   my ($minefield) = @_;
      9   my @heatmap; # array storing our final answer
     10 
     11   # check for no rows
     12   return $minefield if @{ $minefield } == 0;
     13 
     14   # check for no columns
     15   return $minefield if $minefield->[0] eq "";
     16 
     17   # read in minefield spaces and mines into array
     18   # append an extra column with 'X' at the end
     19   my @field = map { [split ( //, $_ ), 'X'] } @{ $minefield };
     20 
     21   my $columns = @{ $field[0] } - 1; # subtract extra column we added
     22   my $rows    = @field;
     23 
     24   # add an extra row of 'X' to the end
     25   push @field => [ ('X') x ($columns + 1) ]; # need that extra column back
     26 
     27   # go through the minefield, first by rows then columns
     28   foreach my $row (0 .. $rows - 1) {
     29 
     30     my $row_buildup = ""; # this represents each row we add to @heatmap
     31 
     32     foreach my $column (0 .. $columns - 1) {
     33       my $mine_count;
     34 
     35       if ( $field[$row][$column] eq '*' ) {
     36         $mine_count = '*'; # replace mine with mine
     37 
     38       } else {
     39 
     40         # count number of mines in the 8 adjacent spaces, including diagonally
     41         foreach my $offset ([ 0, -1], [ 0,  1], [-1,  0], [ 1,  0],
     42                             [-1, -1], [-1,  1], [ 1, -1], [ 1,  1]) {
     43 
     44           if ( $field[$row + $offset->[0]][$column + $offset->[1]] eq '*' )
     45             { $mine_count++; }
     46 
     47         } # end foreach my $offset
     48 
     49         # if count is greater than zero, insert the count
     50         # otherwise, we just insert a space
     51         $mine_count = $mine_count ? $mine_count : ' ';
     52 
     53       }   # end else
     54 
     55       $row_buildup .= $mine_count;
     56 
     57     }     # end foreach my $column
     58 
     59     push @heatmap => $row_buildup; # add the row to our answer
     60 
     61   }       # end foreach my $row
     62 
     63   return \@heatmap;
     64 
     65 }
     66 
     67 1;