Last active
December 19, 2015 13:29
-
-
Save RSully/5962165 to your computer and use it in GitHub Desktop.
PHP implementation of Game Of Life
This file contains 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 | |
// Implementation | |
function iterate($original) | |
{ | |
$board = $original; | |
for ($x = 0; $x < count($board); $x++) { | |
$row = $board[$x]; | |
for ($y = 0; $y < count($row); $y++) { | |
$cell = $row[$y]; | |
$live_neighbors = live_neighbors($original, $x, $y); | |
if ($cell == 1) { | |
// Cell is alive | |
if ($live_neighbors < 2) { | |
$board[$x][$y] = 0; | |
} else if ($live_neighbors > 3) { | |
$board[$x][$y] = 0; | |
} | |
} else { | |
// Cell is dead | |
if ($live_neighbors == 3) { | |
$board[$x][$y] = 1; | |
} | |
} | |
} | |
} | |
return $board; | |
} | |
function live_neighbors($board, $x, $y) | |
{ | |
$neighbors = @array( | |
$board[$x-1][$y-1], $board[$x-1][$y], $board[$x-1][$y+1], | |
$board[$x][$y-1], $board[$x][$y+1], | |
$board[$x+1][$y-1], $board[$x+1][$y], $board[$x+1][$y+1] | |
); | |
return array_sum($neighbors); | |
} | |
// Assume board | |
$board = array( | |
array(1, 0, 1), | |
array(0, 1, 1), | |
array(0, 0, 0) | |
); | |
print_r($board); | |
print_r(iterate($board)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment