Advent of Code 2022— Day 1

Vaclav Hrouda
2 min readDec 8, 2022

--

This is the first article in the series where I share my solutions to the puzzles from the Advent of Code 2022. This year I am using PHP and I created a platform for comfortable development. You can find more details about the platform here and feel free to use it as well.

Day 2 >

Photo by Ashley Levinson on Unsplash

Before you start reading, I encourage you to try to solve the puzzle by yourself.

Calorie Counting

In the first part, we have to find how many calories the elf with the most calories carries. The algorithm for that is simple. We have to count the number of calories each elf is carrying and keep track of the running maximum.

public function run(array $input): int|string
{
$max = 0;
$elf = 0;
foreach ($input as $item) {
if (empty($item)) {
$max = max($max, $elf);
$elf = 0;
continue;
}

$elf += $item;
}

return $max;
}

Part Two

In the second part, we need to find the sum of the three top elves. The most effective algorithm for this task is the Selection algorithm. I will simply modify the solution above to keep track of the running top three values and sum them at the end.

public function run(array $input): int|string
{
$max = [0, 0, 0];
$elf Conclusion= 0;
foreach ($input as $item) {
if (empty($item)) {
$min = array_search(min($max), $max);
$max[$min] = max($max[$min], $elf);

$elf = 0;
continue;
}

$elf += $item;
}

return array_sum($max);
}

Conclusion

The first day is usually warm up and this year wasn’t an exception. The following days will be surely more interesting.

The complete source code of today’s solution can be found on my GitHub.

Do you want to know how I solve the other days? Please follow me here on Medium and don’t miss the following articles.

Day 2 >

--

--