/** * Returns the total brightness of all lights in a {@link LightGrid} * @param LightGrid $grid * @return int total brightness */ public static function totalBrightness(LightGrid $grid) { $sum = 0; foreach ($grid->getGrid() as $row) { $sum += array_sum($row); } return $sum; }
/** * Runs a single {@link LightInstruction} on a {@link LightGrid} applying the * {@link LightInstructionActionBehavior} rules on each light. * * @param LightGrid $lightGrid * @param LightInstruction $instruction * @param LightInstructionActionBehavior $actionBehavior */ public static function run(LightGrid $lightGrid, LightInstruction $instruction, LightInstructionActionBehavior $actionBehavior) { $grid = $lightGrid->getGrid(); $action = $instruction->getAction(); $coordinates = $instruction->getCoordinatePair(); $start = $coordinates[0]; $end = $coordinates[1]; $minY = min($start->getY(), $end->getY()); $yRange = abs($end->getY() - $start->getY()) + 1; for ($x = min($start->getX(), $end->getX()); $x <= max($start->getX(), $end->getX()); $x++) { $lights = array_slice($grid[$x], $minY, $yRange); $lights = array_map($actionBehavior->behaviorForAction($action), $lights); array_splice($grid[$x], $minY, $yRange, $lights); } $lightGrid->setGrid($grid); }
$command = LightSwitchCommand::COMMAND_TOGGLE; break; case 'turn on': $command = LightSwitchCommand::COMMAND_ON; break; case 'turn off': default: $command = LightSwitchCommand::COMMAND_OFF; } return new LightSwitchCommand(Coordinate::fromString($matches[2]), Coordinate::fromString($matches[3]), $command); } } $parser = new CommandParser(); $lightGrid = new LightGrid(new OnOffLightStrategy()); foreach (file('6.txt') as $instruction) { echo 'excecuting ' . $instruction . PHP_EOL; $lightGrid->toggleLights($parser->parseCommand($instruction)); } echo 'Part 1 answer: ' . $lightGrid->getNumLights(true); $lightGrid = new LightGrid(new BrightnessLightStrategy()); foreach (file('6.txt') as $instruction) { echo 'excecuting ' . $instruction . PHP_EOL; $lightGrid->toggleLights($parser->parseCommand($instruction)); } $totalBrightness = 0; foreach ($lightGrid->getLights() as $x => $arr) { foreach ($arr as $y => $brightness) { $totalBrightness += $brightness; } } echo 'Part 2 answer: ' . $totalBrightness;