- Edited
After watching Numberphile: The Light Switch Problem on YouTube this morning, I decided to demonstrate it in PHP during lunch break. I'm sure there are better/cooler ways to do it, but it gets the right result.
<?php
$lights = new Lights();
echo $lights->display();
class Lights {
private $lights = [];
public function __construct() {
foreach (range(0, 9) as $row) {
$this->lights[$row] = array_fill(1, 10, false);
}
foreach(range(1, 100) as $num) {
$this->switcheroo($num);
}
}
public function display(): string {
$result = '';
foreach ($this->lights as $x => $row) {
foreach ($row as $y => $val) {
$num = $x * 10 + $y;
$result .= $val ? str_pad($num, 4, ' ', STR_PAD_LEFT) : ' . ';
}
$result .= "\n";
}
return $result;
}
private function switcheroo(int $num): void {
foreach(range(0, 9) as $row) {
foreach(range(1, 10) as $col) {
if ((($row * 10) + $col) % $num === 0) {
$this->lights[$row][$col] = !$this->lights[$row][$col];
}
}
}
}
}
$ php ~/Desktop/lights.php
1 . . 4 . . . . 9 .
. . . . . 16 . . . .
. . . . 25 . . . . .
. . . . . 36 . . . .
. . . . . . . . 49 .
. . . . . . . . . .
. . . 64 . . . . . .
. . . . . . . . . .
81 . . . . . . . . .
. . . . . . . . . 100