Inception with recursion
Recursion in the most simplest form is a function calling itself over and over again until it doesn’t. In the movie Inception with Leonardo Dicaprio, he is able to navigate through peoples dreams. He is also able to go into a deeper dream in what movie called a dream within a dream, maybe some of you have experience that before. In the movie he was able to continue that process until he reached a place called limbo, were getting out was a very difficult task, almost impossible.
There were also rules with inception. The dreamer needed to have what the movie called a kick that would wake up the dreamer, and prevent him from losing track of reality. The dreamer would need a kick for every level he went deeper. When the dreamer accomplished his goal the kick would wake him up from the dream he was in and it would continue to happen until he was back to reality.
The way I think of a base case is what do I want the function to do once I have achieved my goal, and what should it return. For example lets say we have an object that contains n number of nested objects. We cannot write a bunch of for loops because we don’t know how many we need and the program will just run slower. Take a look at the example below.
The base case is the if statement online 19. It tells the function once the target has been found to stop searching. The return statement will stop the recursive function and return the value. The example below shows a simple recursive function. The recursive function calls its self passing a nested object and will continue to do so until the base has been met.
As you can see this is a simple example and the code would break when the target is not found. Recursive functions can get very complex and they are very powerful. The best way to learn is to practice so give it a try and don’t forget your kick or you will end up in limbo. Until my next post happy coding.