|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\AdventSolutions\Year2016\Day4; |
| 4 | + |
| 5 | +use App\AdventSolutions\AbstractSolution; |
| 6 | + |
| 7 | +class Solution2016Day4 extends AbstractSolution |
| 8 | +{ |
| 9 | + public function solvePart1($input): string |
| 10 | + { |
| 11 | + $sectorIdSum = 0; |
| 12 | + |
| 13 | + foreach ($input as $line) { |
| 14 | + preg_match('/([a-z-]+)-(\d+)\[([a-z]+)]/', trim($line), $matches); |
| 15 | + $encryptedName = str_replace('-', '', $matches[1]); |
| 16 | + $sectorId = intval($matches[2]); |
| 17 | + $checksum = $matches[3]; |
| 18 | + |
| 19 | + $calculatedChecksum = $this->calculateChecksum($encryptedName); |
| 20 | + |
| 21 | + if ($calculatedChecksum === $checksum) { |
| 22 | + $sectorIdSum += $sectorId; |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + return "The sum of sector IDs of real rooms is: <info>$sectorIdSum</info>"; |
| 27 | + } |
| 28 | + |
| 29 | + public function solvePart2($input): string |
| 30 | + { |
| 31 | + foreach ($input as $line) { |
| 32 | + preg_match('/([a-z-]+)-(\d+)\[([a-z]+)]/', trim($line), $matches); |
| 33 | + $encryptedName = $matches[1]; |
| 34 | + $sectorId = intval($matches[2]); |
| 35 | + |
| 36 | + // Decrypt the name |
| 37 | + $decryptedName = $this->decryptName($encryptedName, $sectorId); |
| 38 | + |
| 39 | + // Check if the decrypted name contains "northpole" |
| 40 | + if (str_contains($decryptedName, 'northpole')) { |
| 41 | + return "The sector ID for the North Pole objects is: <info>$sectorId</info>"; |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + return "North Pole objects not found!"; |
| 46 | + } |
| 47 | + |
| 48 | + private function calculateChecksum($name): string |
| 49 | + { |
| 50 | + $letterCounts = count_chars($name, 1); |
| 51 | + $sortedLetters = []; |
| 52 | + |
| 53 | + foreach ($letterCounts as $ascii => $count) { |
| 54 | + $sortedLetters[chr($ascii)] = $count; |
| 55 | + } |
| 56 | + |
| 57 | + uksort($sortedLetters, function ($a, $b) use ($sortedLetters) { |
| 58 | + if ($sortedLetters[$a] === $sortedLetters[$b]) { |
| 59 | + return strcmp($a, $b); |
| 60 | + } |
| 61 | + return $sortedLetters[$b] - $sortedLetters[$a]; |
| 62 | + }); |
| 63 | + |
| 64 | + return implode('', array_slice(array_keys($sortedLetters), 0, 5)); |
| 65 | + } |
| 66 | + |
| 67 | + private function decryptName($name, $sectorId): string |
| 68 | + { |
| 69 | + $decryptedName = ''; |
| 70 | + |
| 71 | + foreach (str_split($name) as $char) { |
| 72 | + if ($char === '-') { |
| 73 | + $decryptedName .= ' '; |
| 74 | + } else { |
| 75 | + $shiftedChar = chr(((ord($char) - ord('a') + $sectorId) % 26) + ord('a')); |
| 76 | + $decryptedName .= $shiftedChar; |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + return $decryptedName; |
| 81 | + } |
| 82 | +} |
0 commit comments