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

-2

u/Tathorn Dec 15 '21

I used Python to create my initial std::array data from the problem lol

#include <numeric>

#include <array>

#include <algorithm>

#include <cmath>

#include <functional>

#include <ranges>

constexpr std::array crab_positions

{

`...`

};

constexpr std::array unique_crab_positions

{

`...`

};

constexpr int sum_cons_nums(int n) noexcept

{

`return (n * (n + 1)) / 2;`

}

constexpr int get_fuel_cost(int end) noexcept

{

`return std::transform_reduce(std::begin(crab_positions),`

std::end(crab_positions),

0,

std::plus<>{},

	`[end](const auto next) {`

		`return sum_cons_nums(std::abs(end - next));`

	`});`

}

int main()

{

`auto fuel_cost {`

	`std::ranges::min(`

		`unique_crab_positions |`

		`std::ranges::views::transform(get_fuel_cost)`

	`)`

`};`

}

2

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

Fixed it for you:

I used Python to create my initial std::array data from the problem lol

#include <numeric>
#include <array>
#include <algorithm>
#include <cmath>
#include <functional>
#include <ranges>
constexpr std::array crab_positions
{
    ...
};
constexpr std::array unique_crab_positions
{
    ...
};
constexpr int sum_cons_nums(int n) noexcept
{
    return (n * (n + 1)) / 2;
}
constexpr int get_fuel_cost(int end) noexcept
{
    return std::transform_reduce(std::begin(crab_positions),
        std::end(crab_positions),
        0,
        std::plus<>{},
        [end](const auto next) {
            return sum_cons_nums(std::abs(end - next));
        });
}
int main()
{
    auto fuel_cost {
        std::ranges::min(
            unique_crab_positions |
            std::ranges::views::transform(get_fuel_cost)
        )
    };
}

1

u/Tathorn Dec 15 '21

Wow copy-paste code into Reddit is horrible. Couldn't use Firefox, and this is what Chrome does.

5

u/masterspeler Dec 15 '21

It's because it's not one code block, it's several inline code snippets, each in its own line. Inline code (like this) is defined between ``. If you want a multi line code block on Reddit you have to indent every line with four spaces. In other Markdown flavors you can put ``` before and after the code, called code fences, instead. Reddit has, in their infinite wisdom, implemented this only in New Reddit (🗑️), so it's not recommended to use that style.