Created
December 1, 2023 16:26
-
-
Save nicoder/232236f1927be8e164b7264578bfd56d to your computer and use it in GitHub Desktop.
Revisions
-
nicoder created this gist
Dec 1, 2023 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,52 @@ <?php // https://adventofcode.com/2023/day/1/answer $lines = file('data.txt'); $calibrationValues = getCalibrationValues($lines); $sum = array_sum($calibrationValues); /** * @return int[] */ function getCalibrationValues(array $lines): array { return array_map(getCalibrationValue(...), $lines); } function getCalibrationValue(string $line): int { $digits = getDigits(replaceTextualDigits($line)); return $digits[0] * 10 + $digits[count($digits) - 1]; } function replaceTextualDigits(string $line): string { $textualDigits = [ 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', ]; $digits = array_flip($textualDigits); $regex = '/' . join('|', $textualDigits) . '/'; return preg_replace_callback( $regex, fn(array $matches) => $digits[$matches[0]], $line ); } /** * @return int[] */ function getDigits(string $line): array { return str_split(preg_replace('/[^\d]/', '', $line)); }