|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Failedcode\Aoc2022\Days; |
| 4 | + |
| 5 | +class Day4 extends AbstractDay |
| 6 | +{ |
| 7 | + public function solve_part_1(): string |
| 8 | + { |
| 9 | + $ranges = $this->getInputRanges(); |
| 10 | + $containSum = 0; |
| 11 | + foreach ($ranges as $range) { |
| 12 | + list($r1s, $r1e, $r2s, $r2e) = $range; |
| 13 | + if (($r2s >= $r1s && $r2e <= $r1e) || ($r1s >= $r2s && $r1e <= $r2e)) { |
| 14 | + $containSum += 1; |
| 15 | + } |
| 16 | + } |
| 17 | + return $containSum; |
| 18 | + } |
| 19 | + |
| 20 | + public function solve_part_2(): string |
| 21 | + { |
| 22 | + $ranges = $this->getInputRanges(); |
| 23 | + $containSum = 0; |
| 24 | + foreach ($ranges as $range) { |
| 25 | + list($r1s, $r1e, $r2s, $r2e) = $range; |
| 26 | + if ($this->isInRange($r1s, $r2s, $r2e) || |
| 27 | + $this->isInRange($r1e, $r2s, $r2e) || |
| 28 | + $this->isInRange($r2s, $r1s, $r1e) || |
| 29 | + $this->isInRange($r2e, $r1s, $r1e)) { |
| 30 | + $containSum += 1; |
| 31 | + } |
| 32 | + } |
| 33 | + return $containSum; |
| 34 | + } |
| 35 | + |
| 36 | + protected function isInRange($x, $start, $end) |
| 37 | + { |
| 38 | + return $x >= $start && $x <= $end; |
| 39 | + } |
| 40 | + |
| 41 | + protected function getInputRanges() |
| 42 | + { |
| 43 | + $inputList = $this->util->loadInput(4); |
| 44 | + $ranges = []; |
| 45 | + foreach ($inputList as $row) { |
| 46 | + if (preg_match('~(\d+)-(\d+),(\d+)-(\d+)~', $row, $matches)) { |
| 47 | + $ranges[] = array_slice($matches, 1); |
| 48 | + } |
| 49 | + } |
| 50 | + return $ranges; |
| 51 | + } |
| 52 | +} |
0 commit comments