Skip to content

Instantly share code, notes, and snippets.

@VladaHejda
Created February 5, 2016 11:27
Show Gist options
  • Save VladaHejda/5257e47d7be036e55c55 to your computer and use it in GitHub Desktop.
Save VladaHejda/5257e47d7be036e55c55 to your computer and use it in GitHub Desktop.
1-D cellular automat. Call as cell.php <rule 0-255 or "loop"> <initial 64bit signed int>
<?php
$rule = $argv[1] ?? null;
$initial = $argv[2] ?? null;
$cellsCount = 64;
$loop = false;
$loopSteps = 50;
function randInitial($cellsCount) {
$initial = '';
while ($cellsCount--) {
$initial .= (string) mt_rand(0, 1);
}
return $initial;
}
if ($rule === 'loop') {
$loop = true;
$rule = null;
}
$resetInitial = isset($initial);
$initial = $resetInitial ? decbin((int) $initial) : null;
do {
if ($loop) {
$rule = $rule ?? -1;
$rule++;
$loop = $rule < 255;
$initial = $resetInitial ? null : $initial;
} else {
$rule = $rule ?? rand(0,255);
}
$initial = $initial ?? randInitial($cellsCount);
echo sprintf("Rule: %d\n", $rule);
$row = [];
for ($i = 0; $i < $cellsCount; $i++) {
$row[] = (bool) ($initial[$i] ?? false);
}
$counter = $loopSteps;
while (!$loop || $counter--) {
$nextRow = [];
$empty = true;
foreach ($row as $i => $cell) {
if ($cell) {
$empty = false;
}
echo $cell ? '*' : ' ';
$prev = ($cellsCount + $i - 1) % $cellsCount;
$next = ($i + 1) % $cellsCount;
$state = (int) $row[$prev] . (int) $cell . (int) $row[$next];
$nextRow[] = (bool) ((2 ** bindec($state)) & $rule);
}
echo "\n";
if ($empty) {
//echo "and nothing has left...\n";
//break;
}
usleep(100000);
$row = $nextRow;
}
usleep(100000);
} while ($loop);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment