Skip to content

Instantly share code, notes, and snippets.

@pwm
Last active July 10, 2017 22:00
Show Gist options
  • Save pwm/c81faee40928c1690e54750cfe0677a3 to your computer and use it in GitHub Desktop.
Save pwm/c81faee40928c1690e54750cfe0677a3 to your computer and use it in GitHub Desktop.
Rule 30
<?php
/**
* Run it: php r30.php
* Run it with a custom number of rows: php r30.php <number>
* Have fun :)
*/
function createRows($numRows, $rule) {
$getNextRow = function ($currRow) use ($rule) {
$nextRow = [0, 0];
for ($i = 1, $iMax = count($currRow) - 1; $i < $iMax; $i++) {
$nextRow[] = $rule[$currRow[$i - 1] . $currRow[$i] . $currRow[$i + 1]];
}
array_push($nextRow, 0, 0);
return $nextRow;
};
$rows[0] = [0, 0, 1, 0, 0];
for ($i = 1; $i <= $numRows; $i++) {
$rows[$i] = $getNextRow($rows[$i - 1]);
}
return $rows;
}
function displayRows($rows, $isDownwards, $micSleep) {
$rowCount = count($rows);
$getRow = function ($rows, $isDownwards) use ($rowCount) {
if ($isDownwards === true) {
for ($i = 0; $i < $rowCount; $i++) {
yield [$i, $rows[$i]];
}
} else {
for ($i = $rowCount - 1; $i >= 0; $i--) {
yield [$i, $rows[$i]];
}
}
};
foreach ($getRow($rows, $isDownwards) as [$pad, $row]) {
echo str_repeat(' ', $rowCount - $pad);
foreach ($row as $cell) {
echo $cell === 1 ? '█' : ' ';
}
echo PHP_EOL;
usleep($micSleep);
}
}
// https://en.wikipedia.org/wiki/Rule_30
const RULE_30 = [
'111' => 0,
'110' => 0,
'101' => 0,
'100' => 1,
'011' => 1,
'010' => 1,
'001' => 1,
'000' => 0,
];
$numRows = isset($argv[1]) && (int)$argv[1] > 0 && (int)$argv[1] <= 1000 ? (int)$argv[1] : 80;
$rows = createRows($numRows, RULE_30);
while (true) {
displayRows($rows, true, 5000);
displayRows($rows, false, 5000);
}
@ozh
Copy link

ozh commented Jul 10, 2017

https://3v4l.org/bO716 if you're curious and lazy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment