AOC 2022 Day 1: Calorie Counting
--
Hi there ! I’m Xavier Jouvenot and today we are going to take a look at the first Advent Of Code puzzle of the year 🎄 (if you are from the future, you can not that the current year is 2022 😉).
For this first “Advent Of Code” post of the year, we are going to tackle the problem from the 1st December 2022 (pretty obviously), named “Calorie Counting”. The solution I will propose in c++, but the reasoning can be applied to other languages.
Self promotion: You can find other articles on computer science and programming on my website 😉
Part 1
The Problem
The full version of this problem can be found directly on the Advent of Code website, I will only describe the essence of the problem here:
Today, we are helping the elves, going through a forest, to manage their food. We need to know which elf has the most food, and to do so, we are going to rely on the calories. We know, for each elf, the number of items they have, and the calories of each item. Those information are given like so:
1000
2000
3000
4000
5000
6000
For example, here, we have the list of items for 3 elves (separated by the empty lines).
Our first mission of the year is to find the maximum amount of calories detained by one elf.
Solution
Here is the complete solution, so that you can get a feel about it, but don’t worry, we are going to explain it, step by step 😉
using Calories = size_t;
PuzzleSolution computeSolution(const std::string_view input) {
auto it = input.begin();
Calories maxCaloriesCarryByOneElf = 0;
Calories caloriesCarriedByCurrentElf = 0;
while (it != input.end()) {
if (*it == '\n') {
maxCaloriesCarryByOneElf =
std::max(maxCaloriesCarryByOneElf, caloriesCarriedByCurrentElf);
caloriesCarriedByCurrentElf = 0;
++it;
continue;
}
auto endOfNumber = std::find(it, input.end(), '\n');
caloriesCarriedByCurrentElf += std::stoi(std::string(it, endOfNumber));
it = std::next(endOfNumber);
}
// last elf
maxCaloriesCarryByOneElf =
std::max(maxCaloriesCarryByOneElf, caloriesCarriedByCurrentElf);
return maxCaloriesCarryByOneElf;
}