Advent Of Code Day 1

Advent of Code has started again - here is a PHP solution to Day 1 - including two code-golfed variants :)

The task for day 1 is simple:

You are given an input file with a bunch of integers, one per line, and need to add them all up.

My quick solution for both parts:

$lines = file(__DIR__ . '/input', FILE_IGNORE_NEW_LINES);
$frequency = 0;
foreach ($lines as $change) {
    $frequency += $change;

echo $frequency;

// part 2
$frequency = 0;
$history = [];
while (true) {
    foreach ($lines as $change) {
        if (isset($history[$frequency])) {
            echo $history[$frequency];
            break 2;
        $history[$frequency] = $frequency;
        $frequency += $change;

And here is the golfed version for part 1, with just 38 bytes of code:


You can see some simple tricks in use here like:

  • $f is not initialized - adding to an un-defined variable will cast it to an integer, and assume value 0
  • the whitespace after echo can be removed in many cases
  • the closing PHP tag is never required

Actually, there is an even shorter solution, depending how you will rename the input file:

comments powered by Disqus