commit e53dfa5af195311e99b27a8d6248c4c8c739e440
parent 35c2cdcf8842ea1df2e6bc1d0189f1c74babe9e4
Author: Samir Parikh <noreply@samirparikh.com>
Date: Tue, 15 Feb 2022 01:23:05 +0000
get all tests to pass for minesweeper
Diffstat:
1 file changed, 55 insertions(+), 13 deletions(-)
diff --git a/minesweeper/Minesweeper.pm b/minesweeper/Minesweeper.pm
@@ -6,20 +6,62 @@ our @EXPORT_OK = qw<annotate>;
sub annotate {
my ($minefield) = @_;
- print "start of minefield....\n";
- print "$_\n" foreach (@{ $minefield });
- print "end of minefield...\n";
-# my @field;
-# foreach my $row (@{ $minefield }) {
-# push @field => [split ( //, $row ), 'X'];
-# }
+ my @heatmap; # array storing our final answer
+
+ # check for no rows
+ return $minefield if @{ $minefield } == 0;
+
+ # check for no columns
+ return $minefield if $minefield->[0] eq "";
+
+ # read in minefield spaces and mines into array
+ # append an extra column with 'X' at the end
my @field = map { [split ( //, $_ ), 'X'] } @{ $minefield };
- print "----\n";
- foreach my $row (@field) {
- print @{ $row }, "\n";
- }
- print "----\n";
- return undef;
+
+ my $columns = @{ $field[0] } - 1; # subtract extra column we added
+ my $rows = @field;
+
+ # add an extra row of 'X' to the end
+ push @field => [ ('X') x ($columns + 1) ]; # need that extra column back
+
+ # go through the minefield, first by rows then columns
+ foreach my $row (0 .. $rows - 1) {
+
+ my $row_buildup = ""; # this represents each row we add to @heatmap
+
+ foreach my $column (0 .. $columns - 1) {
+ my $mine_count;
+
+ if ( $field[$row][$column] eq '*' ) {
+ $mine_count = '*'; # replace mine with mine
+
+ } else {
+
+ # count number of mines in the 8 adjacent spaces, including diagonally
+ foreach my $offset ([ 0, -1], [ 0, 1], [-1, 0], [ 1, 0],
+ [-1, -1], [-1, 1], [ 1, -1], [ 1, 1]) {
+
+ if ( $field[$row + $offset->[0]][$column + $offset->[1]] eq '*' )
+ { $mine_count++; }
+
+ } # end foreach my $offset
+
+ # if count is greater than zero, insert the count
+ # otherwise, we just insert a space
+ $mine_count = $mine_count ? $mine_count : ' ';
+
+ } # end else
+
+ $row_buildup .= $mine_count;
+
+ } # end foreach my $column
+
+ push @heatmap => $row_buildup; # add the row to our answer
+
+ } # end foreach my $row
+
+ return \@heatmap;
+
}
1;