Hanoi towers iterative function
I made this recursive function of the Hanoi Towers where you have to put the number of discs and it returns the number of movements... it works well but I would like to know how to make an iterative function for this...
Here is my function...
Create function fnuHanoi (@Nro int)
returns int
as
begin
Declare @Result int
If @Nro = 1
Set @Result = 1
else
Set @Result = (((dbo.fnuHanoi(@Nro-1))*2)+1)
return @Result
end
go
I have tried with something like this...
Create function fnuHanoi (@Nro int)
returns int
as
begin
Declare @Discs int
Declare @i int
Set @Discs = 1
Set @i = 1
while (@Discs <= @Nro)
begin
Set @i = (@i * 2) + 1
end
return @i
end
go
I'm so sorry for asking this but I would like to understand more about the difference between iterative and recursive functions and when is better to use开发者_开发问答 one instead of the other... Thanks!!!
I'm not familiar with the SQL syntax, so I'll just try to explain as best as I can.
In a linear recursion case like this (i.e. only one recursive call at a time), the way to translate it into an iterative function it to think in reverse of the recursive style. Rather than start at Nro and work your way down to 1, you can start at 1 and work your way up to Nro.
So in the iterative method, result
begins as 1. Then you can iterate from 2 up to Nro. In each iteration, you double the result and then add one.
Here's another possible perspective. In the recursive style, you basically have Nro number of nested function calls. When the deepest one finishes (i.e. when Nro is 1), then the next one up can finish (when Nro is 2), and then the next one, and it continues to bubble back up until you get back to the original invocation. The iterative method follows the bubbling behaviour (as far as the order of the calculation goes). The bubbling starts at 1 - so does the iteration. The bubbling also finishes at Nro, just like the iteration.
Iteration doesn't actually do any of this "bubbling", nor do the concepts depend in any way upon each other. But it might help to think this way to start, at least while you're make this transition.
精彩评论