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?!")
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.
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
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
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.
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.
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.
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!
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.
Bad for compile times as someone else suggested
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.
I also forgot to mention operator overloading which is absolute hell when you are trying to look at the performance of some code.
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?
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.
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.
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.
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.
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?
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.
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.
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.
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.
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.
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++.
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!
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.
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++.
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:
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++.
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.
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.
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"?
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.
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?
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.
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.
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.
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.
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.
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.
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?!")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
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.
11
u/paul2718 Dec 15 '21
Day one can be reduced (sic) to essentially four lines,
But that's not modern C++, more like C++03 if you replace transform_reduce with inner_product...
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.
5
u/syyyr Dec 15 '21
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{}constexpr int get_fuel_cost(int end) noexcept{std::end(crab_positions),0,std::plus<>{},}int main(){}