Skip to content

Instantly share code, notes, and snippets.

@nicoder
Created December 1, 2023 16:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicoder/232236f1927be8e164b7264578bfd56d to your computer and use it in GitHub Desktop.
Save nicoder/232236f1927be8e164b7264578bfd56d to your computer and use it in GitHub Desktop.
<?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));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment