Created
September 16, 2011 08:59
-
-
Save cordoval/1221617 to your computer and use it in GitHub Desktop.
Spike for functionally solving MineSweeper Kata
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
<?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