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

24

u/wheypoint Ö Dec 15 '21

Great to see c++20 in action and nice write ups

I really like that modern c++ is getting these more functional features but tbh i think they aren't what i'd use here. I Think it's great when some raw loop can be replaced by some more readable desciptive algorithm, even better if it leads to shorter code. But do people really think

uint32_t count_increasing_windows(std::istream &input) {
  auto sliding_window_view = std::ranges::istream_view<uint32_t>(input) 
| std::ranges::views::transform([e1 = 0, e2 = 0, e3 = 0](uint32_t curr) mutable {
    e1 = std::exchange(e2, std::exchange(e3, curr));
    return e1 + e2 + e3;
    });
  return std::ranges::count_if(sliding_window_view, 
                           [prev = std::numeric_limits<uint32_t>::max(), drop = 2]
                           (uint32_t curr) mutable {
                              if (drop > 0) {
                                drop--;
                                return false;
                              }
                              return std::exchange(prev, curr) < curr; });}

is more readable than the equivalent super simple index or iterator based for loop?

Now maybe in haskell you could solve this using a nice functional composition of simple functions but i think it's too much for c++ ranges.

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)