Created
March 22, 2011 15:41
-
-
Save masak/881437 to your computer and use it in GitHub Desktop.
Minesweeper kata - the code I end up with
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use v6; | |
module Minesweeper; | |
sub sweep($input) is export { | |
my @field = ([.comb] for $input.lines); | |
my $rows = @field.elems; | |
my $columns = @field[0].elems; | |
sub neighbors($i, $j) { | |
my $neighbors = 0; | |
for [-1, -1], [-1, 0], [-1, 1], | |
[ 0, -1], ( ), [ 0, 1], | |
[ 1, -1], [ 1, 0], [ 1, 1] -> [$di, $dj] { | |
next unless 0 <= $i + $di < $rows; | |
next unless 0 <= $j + $dj < $columns; | |
if @field[$i + $di][$j + $dj] eq '*' { | |
$neighbors++; | |
} | |
} | |
return $neighbors; | |
} | |
my @result = map -> $i { | |
(neighbors($i, $_) for 0 ..^ $columns).join; | |
}, 0 ..^ $rows; | |
return @result.join("\n"); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use v6; | |
use Test; | |
use Minesweeper; | |
is sweep('.'), '0', 'empty 1x1 board'; | |
is sweep('....'), '0000', 'empty 1x4 board'; | |
is sweep('*.*.'), '0201', '1x4 board with bombs'; | |
{ | |
my $input = <.. ..>.join("\n"); | |
my $output = <00 00>.join("\n"); | |
is sweep($input), $output, '2x2 empty board'; | |
} | |
{ | |
my $input = <.* **>.join("\n"); | |
my $output = <32 22>.join("\n"); | |
is sweep($input), $output, '2x2 empty board'; | |
} | |
done; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment