[php] AOC day 11 part 2
Viewer
*** This page was generated with the meta tag "noindex, nofollow". This happened because you selected this option before saving or the system detected it as spam. This means that this page will never get into the search engines and the search bot will not crawl it. There is nothing to worry about, you can still share it with anyone.
- #!/usr/local/bin/php
- <?php
- class CellularSeats {
- public $grid = [];
- private $rows;
- private $cols;
- public function __construct() {
- $this->grid = file(__DIR__.'/input.txt');
- $this->grid = array_map('trim', $this->grid);
- $this->grid = array_map('str_split', $this->grid);
- $this->rows = sizeof($this->grid);
- $this->cols = sizeof($this->grid[0]);
- }
- public function part2()
- {
- $grid = $this->grid;
- $changed = true;
- $new_grid = $grid;
- while($changed) {
- $changed = false;
- for ($line=0; $line < $this->rows; $line++) {
- for ($col=0; $col < $this->cols; $col++) {
- switch ($grid[$line][$col]) {
- // If a seat is empty (L) and there are no occupied seats adjacent to it, the seat becomes occupied.
- case 'L':
- if ($this->count_neighbors($grid, $line, $col) == 0) {
- $new_grid[$line][$col] = '#';
- $changed = true;
- }
- break;
- // If a seat is occupied (#) and four or more seats adjacent to it are also occupied, the seat becomes empty.
- // Also, people seem to be more tolerant than you expected: it now takes five or more visible occupied seats for an occupied seat to become empty
- case '#':
- if ($this->count_neighbors($grid, $line, $col) >= 5) {
- $new_grid[$line][$col] = 'L';
- $changed = true;
- }
- break;
- // Otherwise, the seat's state does not change.
- default:
- break;
- }
- }
- }
- $grid = $new_grid;
- }
- // count occupied seats
- $grid = array_map('implode', $grid);
- $grid = implode($grid);
- return substr_count($grid, '#');
- }
- private function count_neighbors($grid, $row, $col) {
- $neighbors = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]];
- $result = 0;
- foreach ($neighbors as $offset) {
- $factor = 1;
- while (isset($grid[$row + $factor*$offset[0]][$col + $factor*$offset[1]]) && $grid[$row + $factor*$offset[0]][$col + $factor*$offset[1]] == '.') {
- $factor += 1;
- }
- if (isset($grid[$row + $factor*$offset[0]][$col + $factor*$offset[1]]) && $grid[$row + $factor*$offset[0]][$col + $factor*$offset[1]] == '#') {
- $result += 1;
- }
- }
- return $result;
- }
- }
- $cs = new CellularSeats();
- $part2 = $cs->part2();
- echo("Part 2 occupied: $part2\n");
Editor
You can edit this paste and save as new: