Skip to content

Instantly share code, notes, and snippets.

@nicoder
Created December 1, 2023 16:26
Show Gist options
  • Save nicoder/232236f1927be8e164b7264578bfd56d to your computer and use it in GitHub Desktop.
Save nicoder/232236f1927be8e164b7264578bfd56d to your computer and use it in GitHub Desktop.

Revisions

  1. nicoder created this gist Dec 1, 2023.
    52 changes: 52 additions & 0 deletions advent_of_code_day_1.php
    Original 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));
    }