|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Year2023\Day05; |
| 4 | + |
| 5 | +#$input = file_get_contents('example.txt'); |
| 6 | +$input = file_get_contents('input.txt'); |
| 7 | + |
| 8 | +class Map |
| 9 | +{ |
| 10 | + /** @var Range[] */ |
| 11 | + private array $ranges = []; |
| 12 | + public function __construct(string $input) |
| 13 | + { |
| 14 | + $lines = explode("\n", $input); |
| 15 | + array_shift($lines); |
| 16 | + foreach ($lines as $line) { |
| 17 | + $this->ranges[] = new Range($line); |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + public function convert(int $in): int |
| 22 | + { |
| 23 | + foreach ($this->ranges as $range) { |
| 24 | + if (null !== ($result = $range->convert($in))) { |
| 25 | + return $result; |
| 26 | + } |
| 27 | + } |
| 28 | + return $in; |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +class Range |
| 33 | +{ |
| 34 | + private int $destination; |
| 35 | + private int $source; |
| 36 | + private int $length; |
| 37 | + public function __construct(string $input) |
| 38 | + { |
| 39 | + [$this->destination, $this->source, $this->length] = explode(" ", $input); |
| 40 | + } |
| 41 | + |
| 42 | + public function convert(int $in): ?int |
| 43 | + { |
| 44 | + if ($in >= $this->source && $in <= $this->source + $this->length) { |
| 45 | + return $in - ($this->source - $this->destination); |
| 46 | + } |
| 47 | + return null; |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | + |
| 52 | + |
| 53 | +$blocks = explode("\n\n", $input); |
| 54 | +$seeds = explode(" ", array_shift($blocks)); |
| 55 | +array_shift($seeds); |
| 56 | + |
| 57 | +$maps = []; |
| 58 | +foreach ($blocks as $block) { |
| 59 | + $maps[] = new Map($block); |
| 60 | +} |
| 61 | + |
| 62 | +$locations = []; |
| 63 | +foreach ($seeds as $seed) { |
| 64 | + $location = $seed; |
| 65 | + foreach ($maps as $map) { |
| 66 | + $location = $map->convert($location); |
| 67 | + } |
| 68 | + |
| 69 | + $locations[] = $location; |
| 70 | + echo $seed, " -> ", $location, "\n"; |
| 71 | +} |
| 72 | + |
| 73 | +echo "lowest: ", min($locations); |
| 74 | + |
| 75 | +echo "\n"; |
| 76 | + |
| 77 | + |
0 commit comments