This is my week 7 SLOG entry, on the topic of recursion. In computer science, recursion is essentially writing methods/functions that complete a task by calling on themselves a finite number of times. Whenever you write a recursive function it is essential to have what is called a "base case . A base case is essentially an iteration of a recursive function that does not involve calling itself, and if you do not have a base case your program will crash when you call the function because it will call itself an infinite number of times and you will get an error saying "Maximum recursion depth exceeded". Recursion is useful because it can help you do complicated tasks by relating them to their most simple cases. For example, consider the Towers of Hanoi problem with three stools, where you have to move rings from one stool to another stool but you cannot place a large . Though this problem seems complicated, it can be coded very simply using recursion. Your recursive method could use the following logic:
If there is only one cheese on the stool, move it to the destination
Else: Recursively call this function to move all cheeses except for one to an intermediate stool
Move the bottom cheese to the destination stool
Recursively call your function to move all cheeses from the intermediate stool to the destination stool.
This shows how recursion can solve more complicated problems by reducing them to their simplest cases.
No comments:
Post a Comment