Reputation: 43
I tried to write recursive function for Fibonacci sequence. I used an array to save precalculated elements to improve algorithm(which is a common way to do).
Here is my code:
var n = Int(readLine()!)
var arr = [Int](repeating:0, count:n!)
arr[0] = 1
arr[1] = 1
arr[2] = 2
func fib(n : Int, arr: inout [Int]) -> (Int,[Int]){
if arr[0] != 0 {
return (arr[n],arr)
}
arr[n] = fib(n: n - 1,arr: &arr).0 + fib(n: n - 2,arr: &arr).0
return (arr[n],arr)
}
n! -= 1
print(fib(n:n! ,arr: &arr).0)
Notice: 3 < n
The answer for any integer as n is 0.
How can I fix it?
I know that using global variables are much easier(for saving operation), but i don't know how to do that.
Upvotes: 1
Views: 758
Reputation: 1
func fibonacciOf(_ number: Int) -> Int {
if number == 1 || number == 2 {
return 1
}
return fibonacciOf(number - 2) + fibonacciOf(number - 1)
}
print(fibonacciOf(5))
Upvotes: 0
Reputation: 272770
The mistake seems to be in the first if statement:
if arr[0] != 0 {
return (arr[n], arr)
}
If the first element of the array is not 0, then you return arr[n]
. Well, arr[0]
is always 1, so the condition is always true, but arr[n]
is initially 0 for all n >= 3, which is what caused the observed behaviour.
I think you meant to say:
if arr[n] != 0 {
Also, the function doesn't need to return the array since you are using inout
- passing the array by reference. You are not using the second item of the tuple anywhere, are you? So the function can be written as:
func fib(n : Int, arr: inout [Int]) -> Int {
if arr[n] != 0 {
return arr[n]
}
arr[n] = fib(n: n - 1,arr: &arr) + fib(n: n - 2,arr: &arr)
return arr[n]
}
Upvotes: 2