Skip to content

Instantly share code, notes, and snippets.

@cordoval
Created September 16, 2011 08:59
Show Gist options
  • Save cordoval/1221617 to your computer and use it in GitHub Desktop.
Save cordoval/1221617 to your computer and use it in GitHub Desktop.
Spike for functionally solving MineSweeper Kata
<?php
$grid = array(
array('*', '*', '*', '*', '*'),
array('*', '.', '*', '.', '*'),
array('*', '*', '.', '.', '*'),
array('*', '*', '.', '*', '*'),
array('*', '*', '*', '*', '*')
);
$neighbourCoords = array(
array(-1, -1),
array(0, -1),
array(1, -1),
array(-1, 0),
array(1, 0),
array(-1, 1),
array(0, 1),
array(1, 1)
);
$findNeighbours = function($grid, $x, $y) use ($neighbourCoords) {
$neighbours = array();
foreach ($neighbourCoords as $increment) {
$targetY = $y + $increment[1];
$targetX = $x + $increment[0];
$neighbours[] = $grid[$targetY][$targetX];
}
return $neighbours;
};
$findMines = function($sum, $cell) {
return $sum += ('*' == $cell) ? 1 : 0;
};
for ($y = 0; $y < 5; $y++) {
for ($x = 0; $x < 5; $x++) {
$neighbours = $findNeighbours($grid, $x, $y);
$mines = array_reduce($neighbours, $findMines, 0);
echo "Mines at $x,$y: $mines\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment