Skip to content

Instantly share code, notes, and snippets.

@mrbellek
Last active December 7, 2023 15:02
Show Gist options
  • Save mrbellek/f4d1d567e5835bbb9cef93d16371bf4d to your computer and use it in GitHub Desktop.
Save mrbellek/f4d1d567e5835bbb9cef93d16371bf4d to your computer and use it in GitHub Desktop.
Advent of Code 2023 - day 1
<?php
declare(strict_types=1);
$input = file('input.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$sumOfNumbers = 0;
foreach ($input as $line) {
printf('turned %s into ', $line);
$line = replaceNumberWordsWithDigits($line);
printf('%s' . PHP_EOL, $line);
$digits = getFirstAndLastDigitsFromLine($line);
$number = intval($digits[0] . $digits[1]);
$sumOfNumbers += $number;
}
printf('The total sum of all numbers is: %s' . PHP_EOL, $sumOfNumbers);
function getFirstAndLastDigitsFromLine(string $line): array
{
$justDigits = preg_replace('/[^0-9]/', '', $line);
if (strlen($justDigits) < 1) {
throw new RuntimeException(sprintf('er is niets over van regel %s' . PHP_EOL, $line));
}
return [
substr($justDigits, 0, 1),
substr($justDigits, -1),
];
}
function replaceNumberWordsWithDigits(string $line): string
{
//this is just plain evil :(
$line = str_replace(
['oneight', 'threeight', 'fiveight', 'nineight', 'twone', 'threeight', 'fiveight', 'sevenine', 'eightwo', 'eighthree', ],
['18', '38', '58', '98', '21', '38', '58', '79', '82', '83', ],
$line
);
$line = str_replace(
['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'],
['1', '2', '3', '4', '5', '6', '7', '8', '9'],
$line
);
return $line;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment