r/learnprogramming • u/Temporary-Warthog250 • 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
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) } }