|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Year2023\Day15; |
| 4 | + |
| 5 | +$start = microtime(true); |
| 6 | + |
| 7 | +#$in = file_get_contents('example.txt'); |
| 8 | +$in = file_get_contents('input.txt'); |
| 9 | + |
| 10 | +$commands = explode(",", $in); |
| 11 | + |
| 12 | +$boxes = array_fill(0, 256, []); |
| 13 | + |
| 14 | +$part1Sum = 0; |
| 15 | +foreach ($commands as $command) { |
| 16 | + $part1Sum += hash($command); |
| 17 | + |
| 18 | + if (preg_match('/(\w+)([=-])(\d*)/', $command, $out)) { |
| 19 | + [,$label, $operation, $focalLength] = $out; |
| 20 | + } else { |
| 21 | + die('no match'); |
| 22 | + } |
| 23 | + |
| 24 | + $boxNumber = hash($label); |
| 25 | + |
| 26 | + if ($operation === '-') { |
| 27 | + if (isset($boxes[$boxNumber][$label])) { |
| 28 | + unset($boxes[$boxNumber][$label]); |
| 29 | + } |
| 30 | + } elseif ($operation === '=') { |
| 31 | + $boxes[$boxNumber][$label] = $focalLength; |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +$part2Sum = 0; |
| 36 | +foreach ($boxes as $boxNum => $box) { |
| 37 | + foreach (array_values($box) as $lensNum => $focalLength) { |
| 38 | + $part2Sum += ($boxNum+1) * ($lensNum+1) * $focalLength; |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | + |
| 43 | + |
| 44 | + |
| 45 | + |
| 46 | +echo "\n", $part1Sum, "\n"; |
| 47 | +echo "\n", $part2Sum, "\n"; |
| 48 | + |
| 49 | + |
| 50 | +echo microtime(true) - $start; |
| 51 | +echo "\n"; |
| 52 | + |
| 53 | + |
| 54 | +function hash(string $command): int |
| 55 | +{ |
| 56 | + $val = 0; |
| 57 | + for ($i = 0, $iMax = strlen($command); $i < $iMax; $i++) { |
| 58 | + $val += ord($command[$i]); |
| 59 | + $val *= 17; |
| 60 | + $val %= 256; |
| 61 | + } |
| 62 | + |
| 63 | + return $val; |
| 64 | +} |
| 65 | + |
0 commit comments