C++: Advent of Code — Day 1, Part 1

Rud Merriam
One Stop C++
7 min readDec 15, 2023

--

This ongoing series explores functional programming (FP) and the C++ Ranges library, sometimes with some structured programming (SP) for added interest. It is an experiment to learn more about FP and the library. The first article, C++: Advent of Code Introduction, explains the purpose and introduces the framework used daily.

Day 1's problem consists of a list of lines containing encoded coordinates. Each line is a mix of letters and digits. We must extract the first and last digits, append the last digit to the first, and determine the value. Then, do a summation of the line values. Here is the list of test input data, the line values, and the total.

1abc2       ==> 12
pqr3stu8vwx ==> 38
a1b2c3d4e5f ==> 15
treb7uchet ==> 77
------------------
sum ==> 142

A high-level analysis finds these activities:

  1. Iterate through the data to obtain a line,
  2. Calculate the value of a line,
  3. Add the line values.

A first pass is:

uint64_t sum { };    
for (auto const& line: get_line) {
sum += line_value(line);
}

The data is a string of characters with line feed separators dividing them into lines. We can use the range for loop to iterate through the range using get_line to extract a…

--

--

Rud Merriam
One Stop C++

I am a retired software engineer with decades of experience with embedded systems and have used C++ since the early 90s.