r/learnprogramming • • Apr 05 '22

Name one programming/comp sci concept you never understood and if you understand it, try to explain it to them

Name a programming concept such as virtual functions, pointers, certain algorithms, etc that you always had a hard time understanding and why.

Someone else who reads yours and does understand it, try to explain it to them to help them learn

1.6k Upvotes

738 comments sorted by

View all comments

2

u/dizzyflames Apr 05 '22

Recursion is weird to me. I kind of understand it but still feel like I don't. You give me a recursion problem and I won't know if it works until I compile it even if it's a pretty basic problem but I still somehow get it working even if I don't know how I did it.

0

u/[deleted] Apr 05 '22

I came up with this explanation in case I’m asked at an interview, so you will be my test monkey for it lol.

Imagine you have a tower of lego. Literally just bricks stacked onto one another vertically. And you decide you want to take it apart.

Your plan is to break off one piece at a time. So you start from the very top, break the topmost piece, and put it on the floor to your left. Now you are left with the tower that has one less pieces. You break off the new top piece and put it aside. You basically repeat this, until your tower is just one lego brick (this is the base condition). When its just one brick left, you put it with the others, and voila, you just recursively dismantled a lego tower. The return part of recursion just means that you are passing the last value up, so the originally called instance of the function receives it.

If we translate into code we get function breakTower(tower) { if(tower.size == 1) { return tower.top } else { tower.breakTopOff() return breakTower(tower) } }

1

u/Liambass Apr 07 '22 edited Apr 07 '22

That description seems more like an iterative approach to me?

"remove bricks until there aren't any more".

I think a better example would be trying to disassemble the tower from the bottom;

void breakTower(Tower tower) {
    breakTowerRecursive(tower, tower.base);
}

void breakTowerRecursive(Tower tower, Brick brick){
    if (brick.above == null) {
        brick.remove();
    } else {
        breakTower(tower, brick.above);
        brick.remove();
→ More replies (2)