the number of disk -1, recall function tower for n-1 disk and move it ‘from’ to ‘to’ Else, call function tower for ‘a-1’ i.e.if number of disk = 1, move it from ‘initial peg’ to the ‘destination peg’ Create a function Tower with int ‘a’ – for number of disks, char ‘from’ – for from peg, char ‘aux’ – for a secondary peg, char ‘to’ – for destination peg.4-disk requires 7+1+7 = 15 steps to be solved. While the 3-disk puzzle required 7 steps. Recursively solve the problem of moving disk 1,2 and 3 from peg C to peg BĮventually, you figure out that there is some pattern to the puzzle and with each increment in disks, the pattern could be followed recursively.Recursively solve the problem of moving disk 1,2, and 3 from peg A to peg C.Would you like to get updates once a month on our latest articles? We won’t spam, we promise. The puzzle is finally completed by moving disk 1 from peg A over disk 2 and 3 at peg B. After which disk 2 can be moved above disk 3 at peg B. Now to solve the problem, recursively move disk 3 from peg A to peg B. So by ensuring that you do not break the rules, using the above subsets of 3 steps in the previous case, you would move disk 1 and 2 to peg C, leaving disk 3 exposed with no disk above it. To move the stack to peg B you would have to expose disk 3 and to do that disk 1 and 2 have to be moved to peg C. You can easily move this stack from peg B to any other peg using these 3 steps.īut what if we have 3 disks – 1,2, and 3 stacked in peg A. Then move disk 2 from peg A to peg B and, finally, move disk 1 from peg C to peg B. The target is to move both these disks to peg B. Take an example with 2 disks: Disk 1 on top of Disk 2 at peg A. Let’s try to solve a puzzle – Tower of Hanoi using recursion. Return x*factorial(x-1) // break into smaller problem(s)ĭetailed explanation to Recursion can be found – Here Tower of Hanoi algorithm explained Let’s take a simple example and try to understand those.įollowing is the pseudo code of finding the factorial of a given number X X using recursion. Recursion is useful in solving problems which can be broken down into smaller problems of the same kind.īut when it comes to solving problems using Recursion there are several things to be taken care of. ![]() ![]() So it’s like there is a function called d r e a m ( ) dream(), and we are just calling it in itself. Leonardo had a dream, in that dream he had another dream, in that dream he had yet another dream, and that goes on. It will be easier for those who have seen the movie Inception. When a function calls itself, it’s called Recursion.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |