r/learnprogramming • • 28d ago

How to train programming logic?

It's easy to learn syntaxis of a programming language, or buttons of a software, but it won't give you the skill, and programmer should learn how to solve problems, but even here it's possible to learn how to do it not in the best way possible, at least I have no idea what you need to do it in a very efficient way.

I just got my mind blown with this:

std::bitset<4> rotLeft(std::bitset<4> x, int n)
{
  return (x<<n) | (x>>(4-n));
}

It's a C++ function to rotate bitset, I would never figure out that it's possible to do it in THAT way, I did it with loop that stores bit that is about to get out of bounds and then putting in the beginning...

How do you even learn this kind of mentality / logic, to come up with such stuff? I just refuse to believe that it's done by practice alone

29 Upvotes

27 comments sorted by

1

u/rbatts94 27d ago

I asked Claude to generate me some coding problems.

I had an old app from my apprenticeship and fixed the old bugs / updated the methods and technologies.

Built apps that really interested me / that my friends would find useful

1

u/Lemenus 26d ago

I asked how to train own brain, not about you using ai, nor how to throw brain into the trash bin

1

u/rbatts94 26d ago

If you don't understand the benefit of taking a decade old codebase and updating it to modern technologies. Find a new career bro

1

u/Lemenus 26d ago

I asked about completely different thing! 

Yet, you've come here to share about the thing nobody asked for, it's almost as if you would come here to share about how you walked out your dog today, and how everyone should have dogs because of how great it is, that's great, but that's completely off topic.

You just shown everyone once again that ai bros are insufferable people that cannot keep themselves shut

1

u/rbatts94 26d ago

Dude you need to chill. Asking an agent to generate you a function to solve, in the issue you're having is not slop or getting it to do the work for you. Also you asked how to solve problems in an efficient way. Thirdly reading through your own old code or someone else's legacy code on the topic you're trying to learn and fixing / updating it can solidify understanding. Finally building apps using the syntax you want to rep will give you understanding of how things can fit together / be achieved in different ways

5

u/Dazzling_Music_2411 28d ago edited 28d ago

You are right, you won't get far by just "practice", whatever that may mean!

You have to fool around with low-level bitwise logic and get familiar with it. It is absolutely full of such shortcut marvels. Get a book on it.

Now, in the example you gave, try to visualize it:

What is a rotation? Well it's a shift (left or right) , where all the bits that were "shoved out" are attached back at the other end, yes?

And what does a bitwise OR (|) do?

So there you have it! First, left-shift x by n positions. The bits at the front will be lost, but never mind, we get them back by right sifting by 4-n positions! We then OR those two numbers to get the result!

Fun, isn't it? It's also the basis of all computing, people were doing this shit way before high-level languages. If you're intrigued by this kind of thing, there's also a good course you can do called Nand2Tetris.

1

u/Jazzlike_Platypus430 28d ago

I got a lot of insight recently talking with my parents who used to program stuff on huge machines in the late 70s. Punch cards, terminals (only one with a screen, mostly used by a local admin), printers etc. Dad told me about encoding some experimental data in triplets of ints, so that no more than 60 bits were used or so, (assuming byte was 16 bit) and it was just enough. (Then the encoded data was punched back on the cards since their university couldn'd get any tape space to actually have it "saved" in a file.)

I've been always overwhelmed by bitwise operations syntax and recently got to basic understanding what these do. Perhaps it's time to experiment with it just for fun.

1

u/Dazzling_Music_2411 28d ago

It's great fun to experiment with and it will give you more insights into programming than you might expect! It should also exorcise that ancient "overwhelm" 😄

1

u/Jazzlike_Platypus430 28d ago

"Hello world" is difficult nowadays 😂

2

u/SetAndRepeat 28d ago

Your loop already captures the idea: shift bits and wrap the ones that fall off. That expression handles whole groups at once. For "1001" rotated left once, "x << 1" gives "0010", "x >> 3" gives "0001", and "|" combines them into "0011".

Studying other solutions is part of learning this. Solve something your way first, then compare approaches and trace a small example on paper. Once you understand why another solution works, close it and try a variation, such as rotating right or using a different width. That tests whether you learned the idea or just recognised the code.

Learning algorithms and bitwise operations gives you techniques to draw on. You aren't expected to independently rediscover everything.

1

u/ReddyKiloWit 28d ago

If one of your first languages was an assembly language it's easier to come up with these boolean "tricks" since you often work with bits.

In this case you'd likely have a single instruction rotate in assembly, but you'd still have a feel for it. (Emulating a "rotate through carry" is a bit harder.)

1

u/Far-Bullfrog161 28d ago

It's not practice alone, but it's also not magic. Tricks like that come from knowing a small toolbox really well, and in this case the toolbox is bitwise operations: shifts, AND, OR, XOR. Once you know a left shift moves bits up and a right shift moves them down, rotating is just 'the bits that fall off one end get OR'd back in at the other', and the one-liner falls out naturally. So the real skill is building up patterns. A habit that helped me a lot: after you solve something your own way, go look at how others solved it and ask what idea they used that you didn't. Then write that idea down in a sentence and re-solve the problem a few days later without looking. That repetition is how those patterns become yours. Also don't feel bad about your loop version. Working but clunky code is the normal first step, and cleaning it up later is a big part of how seniors got good at this.

1

u/Br3ttl3y 28d ago

This one roots from computer architecture and how numbers are stored in memory. If you were an architecture wizard, and were there when the deep magiks were written, you would think of it.

1

u/Positive_Passion4817 28d ago edited 28d ago

I learned about that idea when briefly looking in to assembly language and then later relearned and used it when doing a module at university involving arduinos and trying to control led arrays as rapidly as possible if I remember right.

Sometimes you can be just lucky to stumble across new techniques and ideas. Sometimes it comes from just wondering if there are ways to do something because the way your are doing it seems awkward and you feel there had to be a better way. A bit of googling and usually you find there is.

1

u/Dazzling_Music_2411 28d ago

Yup, this sort of stuff is hugely important in embedded!

1

u/tacocopter 28d ago

Practice, and learning from others. But mostly practice.

Codewars is good for this, as is Leetcode, but Codewars you could probably start just knowing the basics of a language they support.

1

u/Few-Coconut2548 28d ago

Mostly it's exposure, but you can speed it up on purpose. After you solve something with a loop, ask what it looks like as one operation on the whole value. A rotation is a shift left, plus the bits that fell off moved to the other end, and those are just the value shifted right by the remaining width. OR the two together and you're done. Draw 4 bits on paper and do both shifts by hand once; it sticks after that. Two things that help a lot: Hacker's Delight for bit tricks specifically, and solving problems on Exercism or Codewars and then reading the top solutions. That second habit is where most "how did they think of that" moments come from. You write the clunky version, see three cleaner ones, and next time one of them is your first instinct.

1

u/karanpargal 28d ago

Try this with n = 5: it returns 0000, although rotating four bits five places should give the same result as rotating once. For nonnegative counts, adding n %= 4 before the return fixes it. Testing boundary cases gives you a way to pick apart clever solutions you wouldn't have invented yourself.

1

u/Both_Bend_2481 28d ago

Keep learning and practicing. Read stuff??

0

u/mredding 28d ago

I would never figure out that it's possible to do it in THAT way,

Don't undersell yourself.

How do you even learn this kind of mentality / logic, to come up with such stuff?

Typically, by time, exposure, and dwelling on it.

The Ancient Greeks had their own geometry, where you're only allowed a compass and straight edge. THAT'S IT. The question they were obsessed with was if you could square a circle with just that. (Hint: the answer and proof was found in my lifetime.)

It was play.

So someone was looking at rotating a bitset and wondered how concise they could make it. They might have even wondered if A) their hardware could do it in a single instruction, B) if their compilers were programmed where they could generate that instruction, and C) what must the code look like to get that.

Someone got curious. Someone was playing. Someone was very proud and very self satisfied to come up with this. It's elegant, it's novel, it's concise as fuck, and THIS is the implementation behind std::rotl, and it generates a single ROL or RORX instruction on x86.

So don't chalk it up to genius. If you sat down in front of a problem for long enough, treated it as an obsession, and were willing to explore outside the box - never satisfied with what you have, then you too will likely come up with some truly novel solutions eventually.

11

u/[deleted] 28d ago

[removed] — view removed comment

4

u/ACCTAGGT 28d ago

Those that did, probably something to do with some people reading obscure documentation where it shows particular properties and then experiment with it. Just thinking out of the box of why not try it maybe. Something like that? Or am I wrong?