As a product developer, I tend to focus on developing complex solutions and often times forget about coding basics. I constantly write and deploy code, but It's common to get stuck in the product development rut of reusing pre-developed blocks of code throughout the system. In order sharpen my skills. I made it a goal to revisit popular coding exercises and see how I can solve them now that I have a few years of working experience.
The fibonacci sequence came across my path once again! I've been asked how to calculate the sequence in past interviews, and it's fairly straight forward. For those not familiar, here's the sequence:
0 1 1 2 3 5 8 13 21
Essentially, the sum of the first two values is the third value...and the sum of the second and third value is the fourth value, and so on. There's a couple of ways to solve this problem.
Solution #1
The n parameter is basically an index stopping point. In other words, how large do I want the array to be? I set a default array with the first 2 values as a starting point (I could have passed them into the function, but i'm going to keep this simple)
I iterate n times to calculate the sum of the last two values of the array. I access these values simply by using Array.slice(-2). I use the ES6 spread operator to add the sequence array and the sum together. Each time I do that, I decrement n which stops the while loop when n == 2 (2 values were given as default).
let sequence = [0, 1];
while (n > 2) { //adjusted since we started with 2
const [nextToLast, last] = sequence.slice(-2);
sequence = [...sequence, (nextToLast + last)];
n--;
}
return sequence;
};
Solution #2
I thought this is a good case for recursion. We can use most of concepts in #1 with a few minor changes:
if (n == 2) {
return sequence;
}
const [nextToLast, last] = sequence.slice(-2);
return fibonacciRecursive( n - 1, [...sequence, (nextToLast + last)]);
}
console.log("fibonacci recursive =", fibonacciRecursive(9));
like most recursive functions, the first thing I added was a "bail out" check at the beginning of the function. If n == 2, then return the sequence array. If that's not the case, call the current function with n - 1 and pass the spread operator with the sum of the last 2 values (we decrement n each iteration). The function will call itself until n == 2 and then bail out. This recursion function will give the same result as the function in example #1.
I hope this helps!
Comments
Post a Comment