Modern C++ in Advent of Code: Day 11
On day eleven of Advent of Code, we are dealing with a lot of monkey business.
I do encourage you to try to solve it yourself first https://adventofcode.com.
Input
Today’s input is information about monkeys. Because the input is so short and relatively complex, I decided to skip parsing and instead hard-code the information in the code.
To represent each monkey, we need the initial list of items, the “inspect” operation, which changes the “worried” value of an item and the “test” operation, which determines which monkey will be the recipient of the item.
Because monkeys need to be able to throw items to each other, we also need to represent the troop of monkeys and give each monkey a weak pointer to it.
Simulating the monkey business
Simulating the monkeys requires us to work in rounds. In each round, we will have each monkey (in order) inspect all its items, normalize their values (in part one, this means dividing the values by three) and finally throw each item to another monkey based on the result of the test.
Once we have simulated enough rounds, we need to sort the monkeys based on the number of items they have inspected and return the two highest counts multiplied.
For part two, we have the same simulation process; however, since we need to simulate many more rounds and no longer divide by three in the normalization step, the values would get quickly out of hand. So instead, we need a different but equality-preserving operation during the normalization step. Since all the tests operate using modular arithmetic, we can use the same approach.
To make it equality preserving, we need to use the least common multiple of all the arguments used in the test methods.
Links
The repository with a complete solution (including input parsing) is available here: https://github.com/HappyCerberus/moderncpp-aoc-2022.
I post daily Modern C++ content on Twitter, LinkedIn, Mastodon, Medium and Substack.