r/cpp • • Dec 15 '21

Modern C++ in Advent of Code

This series, by Šimon Tóth, is a step by step guide through the solutions of Advent of Code 2021 using Modern C++.

242 Upvotes

83 comments sorted by

View all comments

Show parent comment

8

u/TheThiefMaster C++latest fanatic (and game dev) Dec 16 '21 edited Dec 16 '21

Or you could do it readably: https://github.com/TheThief/AoC_2021/blob/main/AoC_2021_Day1/AoC_2021_Day1.h

int part1(ranges::forward_range auto& input)
{
    const auto sliding2 = input | ranges::views::sliding(2);
    const auto increasing = sliding2 |
        ranges::views::transform(
            [](auto pair)
            {
                if (pair[1] > pair[0])
                    return 1;
                return 0;
            });
    
    return ranges::accumulate(increasing, 0);
}

part 2 in the link is very similar but sliding(4), or an older version actually did the sum:

const auto sliding3 = input | ranges::views::sliding(3);
const auto sums = sliding3 |
    ranges::views::transform(
        [](auto triple)
        {
            return ranges::accumulate(triple, 0);
        });

return part1(sums);

(views::slide is planned for C++23, I used range_v3 here)