r/learnprogramming • • Oct 29 '26

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

View all comments

1

u/Few-Coconut2548 Oct 29 '26

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.