Modern C++ in Advent of Code: Day 8

Šimon Tóth
2 min readDec 8, 2022

--

On the eighth day of Advent of Code, we are tasked with analyzing a map of trees for premium locales. I encourage you to solve it yourself first. https://adventofcode.com

Input

Today’s input is a simple grid of characters. We will take it as std::vector<std::string>.

Counting trees

Our first task is to count trees that are visible from the outside. This effectively means we need to count the unique ascending values from each direction. We also need to take care not to double-count the trees that are visible from multiple directions.

To iterate in each of the four directions, we will need indices, but we can make the iteration easier by relying on std::views::iota which can be easily reversed using std::views::reverse.

Most scenic locale

Our second task is to find the most scenic tree, a tree from the top of which we can see the furthest in each direction.

A tree can see trees that are not blocked, and a tree can be blocked by trees that are the same or taller. Therefore to calculate the distance each tree can see, we need to remember when we last saw a tree that blocks each size of a tree.

Notably, each border tree has zero scenic value, as it can see zero other trees in at least one direction. On top of that, we can also consider the border trees as height nine, as they effectively block the view outside the map.

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.

--

--

Šimon Tóth

20 years worth of Software Engineering experience distilled into easily digestible articles.