Any case different from our base will need some extra calculations to solve the problem. This will be the else part of the statement. Since if we only need to move one disk, we can just pick it up and move it to the right rod! Recursive case In our Towers of Hanoi problem, the easiest or base case will be to move one disk. In the case of our stars, the easiest possible problem is printing one star. The if will always be the easiest version of your problem. What you need to know about recursion is one important pattern that is always present! Base caseĪ recursive function will always consist of an if-statement which has two possible flows. I am aware that in this scenario it is overkill to use recursion but it gives you a great insight into how recursion works. Most likely, your function will look something like this: That number will be the number of starts to print. The only parameter this function will need is a number. What I want you to make right now is a simple function that can print a number of stars. The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function.ĭid you know that was possible? Quite a cool feature, right? A function can call itself in its body! Let’s look at a more practical example. ![]() A topic which most people find hard to learn since it goes against quite a lot of what they already know about programming. A Brief Introduction to Recursionīefore we can solve this problem together, we will first need to learn about something called recursion. ![]() ![]() What we are looking for is a function that can tell us all the steps we need to make to achieve our goal. A larger disk may never be placed on top of a smaller disk.Sounds easy right? Watch out though, because there are some rules! Our goal: Move the tower to the most right rod so that the largest disk is still at the bottom. Starting situation: All disks are on the most left rod with the largest at the bottom and the smallest on the top.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |