C++: Advent of Code — Day 1, Part 1
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:
- Iterate through the data to obtain a line,
- Calculate the value of a line,
- 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…