[php] AOC day 11 part 1
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 part1()
- {
- $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.
- case '#':
- if ($this->count_neighbors($grid, $line, $col) >= 4) {
- $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) {
- if (isset($grid[$row + $offset[0]][$col + $offset[1]]) && $grid[$row + $offset[0]][$col + $offset[1]] == '#') {
- $result += 1;
- }
- }
- return $result;
- }
- }
- $cs = new CellularSeats();
- $part1 = $cs->part1();
- echo("Part 1 occupied: $part1\n");
Editor
You can edit this paste and save as new:
File Description
- AOC day 11 part 1
- Paste Code
- 11 Dec-2020
- 2.5 Kb
You can Share it:
Latest Code Pastes