I'm trying to covert an implementation below to Swift and having difficulty:
var mem = [];
var fibRecursiveMem = function (n) {
if (mem[n]) return mem[n];
if (n<=2) mem[n] = 1;
else {
mem[n] = fibRecursiveMem(n-1) + fibRecursiveMem(n-2);
}
return mem[n];
}
from: https://dev.to/rattanakchea/dynamic-programming-in-plain-english-using-fibonacci-as-an-example-37m1
my implementation in Swift:
var mem = [Int]()
func fib (_ num: Int) -> Int {
if (mem.count - 1 > num) {
return mem[num]
}
if (num<=2) {mem[num] = 1}
else {
mem[num] = fib(num-1) + fib(num-2)
}
return mem[num]
}
Produces index out of range errors.
Now I want to follow the general logic of the original algorithm. What am I doing wrong in the translation?