Skip to content

Instantly share code, notes, and snippets.

@masak
Created March 22, 2011 15:41
Show Gist options
  • Save masak/881437 to your computer and use it in GitHub Desktop.
Save masak/881437 to your computer and use it in GitHub Desktop.
Minesweeper kata - the code I end up with
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");
}
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