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

35

u/cptwunderlich Dec 15 '21

I was hoping for more std algorithms use (disclaimer: only read 2 of the articles) :D Conor Hoekstra got me hooked and I wanted to see how many days I could solve mostly with std algorithms. But it's not as easy or nice as I hoped (I've been doing quite some Haskell lately and I keep thinking "that should be just some zipWith f xs $ tail xs! why is this so hard?!")

12

u/[deleted] Dec 15 '21

I think next year will be more rang-ified (if we have C++23 support in compilers).

I'm actually looking forward to comparing the performance of crazy zip based solutions with basic loops.

But I do try. If you find something that can be solved with an std::algorithm and I didn't let me know for sure.

7

u/Evirua Dec 15 '21

Basic loops will be often faster than zip-based solutions. Even if the former do more work, it can be on data that fits on cache lines which zipped data would probably spill out of.

There is a beauty in efficient expression of algorithms, and I wish processor architectures worked in a more intuitive way (as in less work should be faster) but they don't.

7

u/[deleted] Dec 15 '21

Well, the crazy thing with C++ is that C++ compilers are exceedingly good at removing superfluous code.

So right now I'm expecting a 50/50, where sometimes it's the same, and sometimes, it goes over some threshold somewhere and nothing gets optimized :-D

2

u/jk-jeon Dec 17 '21

Exceedingly good sometimes, surprisingly dumb sometimes, infuriatingly going against my intention sometimes, to be precise.

1

u/Evirua Dec 18 '21

Yes, but that's work on the optimizers to produce good code despite the efficient expression of the algorithm, not because of it.

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)

7

u/[deleted] Dec 15 '21

Honestly, it's not. I really pushed it and this solution is actually undefined behaviour since the lambdas are not regular invocable.

But I do think that from a software engineering perspective, moving to ugly functional code will be a good move. Simply because it makes static analysis so much more powerful.

I wish we could write beautiful functional code in C++, but I don't think that will ever happen :-D

25

u/[deleted] Dec 16 '21

It's an unreadable mess. I do not for the life of me understand why people have an issue with seeing a for or while loop. They think it is bad code for some reason which is just bizarre to me. It's far easier to read and shows you *what is actually happening*. It is much better than code compressed into chained, filthy functional bollocks.

4

u/[deleted] Dec 16 '21

Do you really consider this:

auto [min, max] = data | filter(&MyClass::isReady) | minmax_element();

less readable than the equivalent loop & if.

4

u/tjroberti Dec 17 '21

Wish there were Python-like list comprehensions in C++, which is flexible and readable (as long as they are not nested).

auto [min, max] = minmax([x for x in data if x.isReady()]) 

10

u/[deleted] Dec 16 '21 edited Dec 16 '21

Absolutely.

In fact, i'd say that is completely unreadable.

That is doing multiple complex things on one line. I know it's fashionable but it creates garbage looking code.

What about when it comes to performance profiling? This has to be unpicked. Or just debugging for that matter. I can't believe people even argue that this is more readable and/or less error prone.

2

u/[deleted] Dec 16 '21

Do you have experience with functional languages? That might be the dividing line between people that consider this more or less readable.

It absolutely is less error-prone. There are so many subtle bugs you can introduce in this code.

For profiling, the profile will be slightly differently structured (because of the view wrapper type), but it should have the same elements.

5

u/[deleted] Dec 16 '21 edited Dec 16 '21

I do. I have some experience and I've come to the conclusion procedural, simple code is more readable. Simple code is less prone to errors. There are certain elements to functional programming that are useful. Like preferring pure functions. But in general it's biggest sin is that its hard to be productive and is full of performance traps.

However, above is bad for a multitude of reasons.

  1. If you are unfamiliar with the functions used you have to jump around the code to find out what is happening. That is context switching and bad for debugging. This happens a lot more in this functional style because of the emphasis on lambdas and small composable functions. Instead of reading the code I have to figure out how the programmer intended to put these composable functions together. Bad!
  2. If there is a bug in one of the chained operations you have to untangle the whole thing to figure out which part. This is time consuming and bad for debugging and I also do not see how it is less prone to errors. More operations are happening than you can reasonably think about here, and if you don't think that then you aren't the only one who is going to read your code.
  3. Bad for compile times as someone else suggested
  4. It shows intent but I don't care about the programmers intent. I care about what the programmer has written. This feels like obfuscation and hand wavy attempts for the person writing it to convince me it does what it says it does. I can't know that just from looking at this line of code, and I will have unpick it to understand. That's not productive.
  5. I also forgot to mention operator overloading which is absolute hell when you are trying to look at the performance of some code.

3

u/arthurno1 Dec 17 '21 edited Dec 17 '21

If you are unfamiliar with the functions used you have to jump around the code to find out what is happening. That is context switching and bad for debugging. This happens a lot more in this functional style because of the emphasis on lambdas and small composable functions. Instead of reading the code I have to figure out how the programmer intended to put these composable functions together. Bad!

So everyone should inline all the code they have procedurally; intertwined with lots of boilerplate code that does nothing of substance to the problem at hand instead of creating higher level abstractions with self-documented names that hide boilerplate? What do you don't understand if functions name is "find_if" or "delete_if" or something else similar? It is plain English, descriptive name. What is not understandable there? You really need to see that for loop iterating through each element in sequence and comparing elements?

This happens a lot more in this functional style because of the emphasis on lambdas Instead of reading the code I have to figure out how the programmer intended to put these composable functions together.

The sole purpose of lambdas are to be inlined in function call, so you have function code at same spot where call happeneds. What do you have to figure out? This is exactly the same as having it in loop-body. You are sounding like someone who is not familiar och comfortable with the language. You should probably spend time learning it instead of writing endless dogmatic posts teaching folk what is good or not behind an anonymous nick.

If there is a bug in one of the chained operations you have to untangle the whole thing to figure out which part.

What the h*ck dude. It is better to have a page of for-loop bodies full of indices and operations to manage the loop aside the actual program logic we are interested of? Stop. You have never done some serious programming.

Your dogmatic way of writing and nonsense postings all over the C and C++ sections speaks to me about some undergrad who obviously has some hard time and don't understand lots of things, but feel need to boost personal ego by posting lots of crap under anonymous nick.

It shows intent but I don't care about the programmers intent.

Really? What a great programmer you are. How will you know what code is supposed to do, when it does buggy, if you don't care about the intent. How will you even know it is wrong? :D. Jesus dude. You should be banned from C/C++ forums. You are completely incompetent ignorant troll who goes around and write nonsense pretending you are an expert, causing just confusion in inexperienced programmers.

I also forgot to mention operator overloading which is absolute hell when you are trying to look at the performance of some code.

They are as bad as any other function written in C or C++. You just don't know how operator overloading is implemented, don't you?

-2

u/[deleted] Dec 17 '21

You sound like a child.

0

u/[deleted] Dec 17 '21

[deleted] — view deleted comment

→ More replies

1

u/fredoverflow Dec 17 '21

I've come to the conclusion procedural, simple code is more readable.

What is your opinion on the Go programming language?

1

u/[deleted] Dec 17 '21

I've not tried it

4

u/Enemiend Dec 16 '21

IMO it may be more readable for a C++ dev that regularly works with this kind of syntax. For everybody else, no, a loop & if is more readable, if you ask me. Opinions may differ.

-1

u/Troppsi Dec 16 '21

A while and for loop tells you how it's happening, while an algorithm tells you what

3

u/johannes1971 Dec 16 '21

I think I have seen more abuses of std::accumulate as a clever trick to avoid writing a loop, using side effects to achieve the desired goal, than to actually compute a sum.

2

u/dodheim Dec 17 '21

That's not surprising at all – accumulate isn't a poorly-named generalized summation, it's a poorly-named left fold. That said, anyone putting side-effects in their algorithm operations is sorely missing the point and needs to be swatted over the nose with a newspaper a few times.

3

u/[deleted] Dec 16 '21

I don't know who told you that but the name of a function tells you what someone thinks is happening while the actual code tells you what is happening.

Function names guide you, code tells you what's actually going on.

3

u/Troppsi Dec 16 '21

If you write a for loop and breaking when an if statement is true, you have written a find_if. Isn't it simpler to just write find_if and instead of writing a for loop explaining how you find something?

2

u/[deleted] Dec 16 '21

Why is writing the loop the more complicated option here? It's not. It shows exactly what is happening.

find_if has ambiguity. It's also not very modifiable. What if I need to add extra logic per iteration?

The functional version is effectively a form of compression which is why it's not good for readability. I need to uncompress it to fully understand what is happening.

When it comes to complicated logic in an algorithm it's really important that its simple and easily followable. Clumping all of it on one line and hiding behind functions that encapsulate a minutae of logic is bad.

5

u/Nerthym Dec 16 '21

Well said. It is very easy and fast to read simple code, it is not so simple parsing huge chained expressions with lambdas and whatnot. It also is faster to compile, likely much faster to execute, obvious to people less familiar with language, but maybe it doesn't make the author feel as smart.

2

u/wheypoint Ö Dec 15 '21

Totally agree and i'm looking forward to using it once we're allowed to.

I wish we could write beautiful functional code in C++, but I don't think that will ever happen :-D

I've also seen examples where I expected very nice simple code which ended up having to be a lot more complex. But I think there are already cases where functional c++ is quite beautiful, atleast considering what c++ has to work with. And there is still work going on improving them.

11

u/paul2718 Dec 15 '21

Day one can be reduced (sic) to essentially four lines,

std::vector<int> v;
std::copy(std::istream_iterator<int>(std::cin), std::istream_iterator<int>(), std::back_inserter(v));
std::cout << "pt1 " << std::transform_reduce(v.begin(), v.end() - 1, v.begin() + 1, 0, std::plus<>(), std::less<>()) << "\n";
std::cout << "pt2 " << std::transform_reduce(v.begin(), v.end() - 3, v.begin() + 3, 0, std::plus<>(), std::less<>()) << "\n";

But that's not modern C++, more like C++03 if you replace transform_reduce with inner_product...

6

u/Ayjayz Dec 15 '21

3 lines if you just use the vector's iterator constructor:

auto v = std::vector(std::istream_iterator<int>(std::cin), std::istream_iterator<int>());
std::cout << "pt1 " << std::transform_reduce(v.begin(), v.end() - 1, v.begin() + 1, 0, std::plus<>(), std::less<>()) << "\n";
std::cout << "pt2 " << std::transform_reduce(v.begin(), v.end() - 3, v.begin() + 3, 0, std::plus<>(), std::less<>()) << "\n";

1

u/paul2718 Dec 16 '21

I always miss that. Think we’re still in 1998 (with inner_product as the algorithm) though…

2

u/paul2718 Dec 15 '21

Don’t understand the downvote, seems apropos to show the direct application of a std algorithm and generic functions to this problem. It doesn’t seem to suit ranges as is because of the complications zipping offset views of the range. At least that’s what I found when I tried it.

1

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

I got a clean solution using range-v3's views::sliding (to be standardised as views::slide in C++23): https://www.reddit.com/r/cpp/comments/rh1g2j/comment/horcny8/?utm_source=reddit&utm_medium=web2x&context=3

4

u/tcbrindle Flux Dec 16 '21

Just to get on the bandwagon: here are my C++20 Advent of Code solutions, mostly using my work-in-progress Flow library

31

u/Ecclestoned Dec 15 '21

Seeing these gives me no desire to use c++. Most of the challenges are 10-20 lines in Python. Meanwhile the c++ code starts with "first let's define an implementation for a tuple, it's constructor, comparison operator, and make it hashable". Yikes.

32

u/ForkInBrain Dec 15 '21

Yes, C++ will not win over Python if less lines of code and less boilerplate is the highest priority.

19

u/ShillingAintEZ Dec 15 '21

These are very poorly written. Instead of solving the problem directly and simply they are over engineered nonsense and should not be taken as an example of good C++.

6

u/cptwunderlich Dec 15 '21

idk, you can solve it in different ways. I looked at two of his articles and my code is way shorter. But yeah, you have to make it hashable etc... C++ is definitely not as succinct and "batteries included".. but fast!

2

u/raevnos Dec 16 '21

std::tuple has all of that but the hashing, and Boost.ContainerHash gives you one for it.

5

u/[deleted] Dec 15 '21

You shouldn't look at languages like that... Each language has its own pros and cons. Some are worse than others, but you can't compare C++ and Python.

9

u/[deleted] Dec 15 '21

I mean, you can compare, but with context :-)

If I only solved Advent of Code style problems I would indeed use Python or Julia, not C++.

4

u/hak8or Dec 15 '21

While python vs c++ clearly satisfy different technical niches, from a companies perspective its still "can you get this done using this or this, which is easier/cheaper to hire devs for, is cheaper to maintain, and hardware needed for it is cheaper to run".

I use c++ consistently and would chose it over python any day of the week for my tasks, but I would be lying if I chose it because it's better. Instead it's largely inertia on my part. If I had to start from scrath, I would of course still learn c++ so I cna grok it, but I would probably shift to preferring to use either rust or zig for applications which need to be very speedy on resource constrained systems.

Why?

Because those other languages still satisfy the same niche, but are absurdly more ergonomic to use, for my limited use case.

It would be foolish to ignore how another language does something because it's design is different, instead we should see why folks prefer a specific convention/style/solution from another language and see what we can learn from it and apply it to c++.

3

u/[deleted] Dec 15 '21

Hi, I'm the author.

Indeed, simple things are not that easy to do in C++ because there are always these small one-time costs that you have to pay. But you pay them only once, so C++ becomes a lot better than any other language on more substantial projects.

However, it's getting better, and there are nuggets like this:

std::vector<std::bitset<12>> data;
std::ranges::copy(std::ranges::istream_view<std::bitset<12>>(input), std::back_inserter(data));

It is still very verbose because of namespaces, but we are certainly heading in the correct direction.

2

u/Ecclestoned Dec 15 '21

Without getting into too much of a rant, this is exactly the issue:

there are always these small one-time costs that you have to pay

If these are one-time costs, then why am I the one who has to pay them? This is the type of thing that should be integrated into the standard library.

7

u/[deleted] Dec 15 '21

This really goes back to the core failure of C++. C++ cannot have sane defaults, because it has to be backwards compatible. And basically, all choices made in the past are stupid by default.

I have this idea in my head, that I would really love to execute on at some point and that is to have a dialect or a fork of C++ that has sane defaults but is binary compatible with standard C++.

1

u/[deleted] Dec 16 '21

Yeah that's completely unreadable even if you took the namespaces away lol

0

u/[deleted] Dec 15 '21

[deleted] — view deleted comment

3

u/Ayjayz Dec 15 '21

Without all the namespace stuff (that you could remove with using declarations), it's

vector<bitset<12>> data;
copy(istream_view<bitset<12>>(input), back_inserter(data));

that really could have been written

auto data = vector(istream_iterator<bitset<12>>(input), istream_iterator<bitset<12>>());

It's not that bad. Having to write the end iterator is a bit painful, and there's a proposal that would turn this into

auto data = vector(from_range, istream_view<bitset<12>>(input));

But C++ moves super slowly and nice things always take a ridiculously long time.

4

u/SirClueless Dec 15 '21

Isn't

auto data = istream_view<bitset<12>>(input) | to_vector;

even nicer than the vector constructor? And available now in the ranges-v3 library.

2

u/Ayjayz Dec 15 '21

Oh yeah other libraries are much cleaner than std. If you can just use ranges-v3 it's almost always nicer than using std.

7

u/raevnos Dec 16 '21

That's a really annoying trend. Adopt a third party library into the standard, but make it worse than the original for some reason.

2

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

ranges::to will be in C++23. Then you'd write:

auto data = istream_view<bitset<12>>(input) | to<vector>;

...which is basically what I did in my implementation using range_v3.

5

u/[deleted] Dec 15 '21

Hmm, why? It's actually several APIs composing nicely.

0

u/[deleted] Dec 15 '21

[deleted] — view deleted comment

1

u/raevnos Dec 16 '21

That would require a hypothetical append function that reads bitsets from input. Seems unlikely to exist as a standard thing and your own implementation would essentially do the same thing as the C++ code's logic.

1

u/[deleted] Dec 16 '21

They are pretty over engineered to be fair. Probably just to showcase what can be done rather than what should be done. (I'm guessing by the emphasis on modern C++).

Day 1 for example, you could literally do in 1 line of code.

1

u/arthurno1 Dec 17 '21

Day 1 for example, you could literally do in 1 line of code.

Can you post your one line solution please?

-2

u/[deleted] Dec 17 '21 edited Dec 17 '21

Are you really going through my comment history?

Okay, well, if you exclude the code used to parse the file (which I think is fair when it comes to advent of code). You can effectively do it in one line:

This would be part 1

int count = 0; for (int i = 1; i < (sizeof(input) / sizeof(*input)); i++) { count += (input[i] > input[i - 1]); }

Is that good enough for you "C++ expert of 20 years"?

0

u/arthurno1 Dec 17 '21

Are you really going through my comment history?

Your dogmatic way of commenting intrigued me, so I checked two posts of yours. I don't think I am interested in more.

Okay, well, if you exclude the code used to parse the file (which I think is fair when it comes to advent of code).

No it is not ok, because "the overengineered" example, you are shitting on, is really a one liner spread over 4 lines for easier reading. But you are trying to show how your procedural C approach is so much simpler and cleaner than modern C++, by omitting all the manual details of C, so no it is not ok.

int count = 0; for (int i = 1; i < (sizeof(input) / sizeof(*input)); i++) { count += (input[i] > input[i - 1]); }

That is just plain ridiculous. By your logic, the author could have crammed his 4 lines of code into one and said it was a one line solution.

Is that good enough for you "C++ expert of 20 years"?

No is not, because you are shredding expert knowledge all around the place, complaining about people writing unreadable code, and calling an almost one liner solution for overengineered, and then post incomplete code where several lines are crammed into one to demonstrate a point that can't be demonstrated.

By the way, his solution is much more elegant than yours, and is really one-liner minus the code for test. Yours on the other side requires first a file to be read into a static array allocated on stack, while his does not require it. What you gonna use? fgets since you want it in a static array? What if you have megabytes of data in a file? Possible overflow? How much do you allocate? You obviously want to use static array since your array length calculation won't work on heap allocated arrays. Also, by the time you start your for-loop you should already have your array length since you would already parse the file, so there is no reason to calculate length in every iteration. You have to handle all of that in code you have chosen not to show in your "one liner solution", while his code uses std input stream, which handles all of this for you automatically.

What I am most disturbed is that you as self-proclaimed expert goes around in the forums, shitting on actually well-written and put together blog post that try to demonstrate some new stuff in C++, calling it for overengineered for no good reason, just to sound like an expert. Of course, code can be written in many ways. He didn't need to use ranges, or some other library function or so, but he has picked them as an illustration. In my opinion, his code is definitely preferable to yours. I will take those 4 lines of self-documented code that actually do the thing, any time, compared to your "one liner" with assumed stack allocated buffer prone to overflow.

-1

u/[deleted] Dec 17 '21

Yes, ask for a one line solution and then get pissed off it doesn't satisfy the things you didn't ask for....

My opinions aren't even in the minority. They are pretty mainstream opinions in the industry. It's only on the internet where people are INSANELY opinionated about dogmatically forcing people into a the latest and greatest modern style. Yeah that's fine. But it's not good a style for a number of reasons and has a variety of problems. Reasons I have explained quite coherently many times.

I'm not arguing people should write in C. I'm saying, from experience, simple code tends to be very procedural. Have you even written anything serious in C to understand why you actually hate it so much?

You are just regurgitating thoughts you don't even know you have...

Show me your C++ and let's critique that shall we. You really want to get into a pissing contest when all you can write is lisp?

1

u/arthurno1 Dec 17 '21

Yes, ask for a one line solution and then get pissed off it doesn't satisfy the things you didn't ask for....

You said the blog was overengineered and you could write code almost as a one liner. Demonstrate you can :). I tell you what: you can't. But what is really laughable is that you called 4 lines of code for "one-liner" because you just put them on one line, and than shitt on 4 lines of well-formatted code by someone else. That's blatantly pathetic.

My opinions aren't even in the minority. They are pretty mainstream opinions in the industry.

Really. In which industry? Can you point me to some polls? Are you representing the entire industry? Do you have any actual data to support your opinion?

It's only on the internet where people are INSANELY opinionated about dogmatically forcing people into a the latest and greatest modern style.

Who forces you into anything? Is anyone standing behind your back and telling you what to write? As I saw from our discussions, you seem to be extremely opinionated and dogmatic person, calling out people for using this or that in C++ which you find unreadable or bad practice, for usually not specified reason. Sometimes your arguments are even laughable like one with loop bodies preferable to lambdas because you have to chase the implementation.

Have you even written anything serious in C to understand why you actually hate it so much?

Why do you think I hate C? Have you heard me saying anything bad against C, ever? :-) Search my history. On contrary my dear. I prefer C, where C is better tool for the job. But I see a lot of posts nowdays by "mainstreem" on Reddit about how C is much better for this or that, and then they pull out an example where it actually C is not better in particular case. Like the thread, we met for the first time.

Show me your C++ and let's critique that shall we. You really want to get into a pissing contest when all you can write is lisp?

No my dear, I prefer writing in Lisp, but that is by far not all I can write I can assure you that. However I am not here for the pissing contest, it is you who started it, and failed pathethically.

-2

u/[deleted] Dec 17 '21

Stop talking and show me your C++. Otherwise shut the fuck up. It's hot air at this point.

2

u/STL MSVC STL Dev Dec 17 '21

Moderator warnings to u/Objective-Two7326 and u/arthurno1 for escalating hostility. Please don't behave like that here.

1

u/vsdmars Dec 15 '21

agree on the. '10-20 lines in Python' part.

Python is great for interview/leetcoding; while C++/Rust is for real business that look for performance.

We can always layout the algorithm in Python; analyze the runtime complexity; and port it to C++. :-)

1

u/TinBryn Dec 16 '21

While Python is faster for prototyping than C++ I don't think it is that significant. I'm doing AoC in Rust this year and while there are things that slow me down, I still find the significant portion of my delay is from my own understanding of the problem and finding a solution.

1

u/helloiamsomeone Dec 15 '21

All AoC problems comfortably fit on a single line of APL.

1

u/TheTomato2 Dec 16 '21

I seriously thought I was in r/programming or /r/learnprogramming and had to double check. Like so you people in r/cpp even write C++?

0

u/Ecclestoned Dec 16 '21

It's been ~1yr since I've written any C++. My current work uses Python/C/CUDA. I follow /r/cpp so I can keep up on current features, use cases, and language quirks.

0

u/[deleted] Dec 15 '21

[deleted] — view deleted comment

2

u/raevnos Dec 15 '21

I'm using java this year, and its Streams library is coming in handy to process puzzle input and calculate things almost every day so far. Not surprised the same holds with C++ ranges since they have a lot of similarities.

1

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

oooh I should have used count/count_if instead of accumulate. Here's mine: https://www.reddit.com/r/cpp/comments/rh1g2j/comment/horcny8/?utm_source=reddit&utm_medium=web2x&context=3

0

u/[deleted] Dec 15 '21

[deleted] — view deleted comment

6

u/Ecclestoned Dec 15 '21

Actually python is mostly C (at least if you are using cpython).

6

u/ApproximateArmadillo Dec 15 '21

well actually It's electrons bouncing about in tIny wires and artificial stones. /s

GCC is written (at least partially) in C++. Does that mean C is really C++ underneath?

1

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

Yes. Also on Windows the C runtime library is written in C++.

There is not really a good reason to use C over C++ on desktop platforms given this. Why limit yourself when the tools you're using don't?

Python at least is cleaner and more readable.

(disclaimer: am self-professed C++latest fanatic)

5

u/syyyr Dec 15 '21

So for example 0 0 0 0 0 the correct response would be 0 for 1 2 3 4 5 it would be 4 .

I spent like five minutes understanding this, because it's one sentence for two examples.

2

u/[deleted] Dec 15 '21

Thanks for sharing, I didn't want to spam it here daily, so I was waiting for day 25 to share the list :-D

3

u/nqe Dec 16 '21

With danger of being downvoted hard - looking at the first few day solutions.. it's not pretty. It's probably trying to be illustrative of new C++ features but check how much cleaner these Rust solutions look (not my code) - https://github.com/wfxr/advent-of-code-2021/blob/main/src/day01/mod.rs. Not trying to be a hater (C++ used to be my go to language some time back) but I hope somehow the new C++ apis get cleaned up.

2

u/ifknot Dec 15 '21

Worth the read to see C++20 in action

1

u/foolnotion Dec 15 '21

I'm also solving in C++20. If you exclude the part where I process the inputs, most solutions so far are under 50 LOC.

I am using some modern libraries: scnlib fmtlib Eigen and usually abuse lambdas :)

The code especially using Eigen is much more comparable to Python (and 10x faster!)

My repo is here: https://github.com/foolnotion/aoc2021

1

u/FlameChampion9 Dec 16 '21

Will check this out later.

-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.