I am very new to programming in general and am having a hard time understanding this Fibonacci sequence example:
var fib = [0, 1];
for (var i = 2; i < n; i++) {
fib[ i ] = fib[ i - 1 ] + fib[ i - 2 ];
console.log(fib);
}
On the first iteration, index 2 is equal to 1, simple enough. But, when I try the second iteration with i = 3, I get:
fib[ 3 ] = fib[ 3 - 1 ] + fib[ 3 - 2 ];
fib[ 3 ] = fib[ 2 ] + fib[ 1 ];
fib[ 3 ] = fib[ 3 ];
Where am I going wrong with my thinking? So far I have:
var fib = [0,1,1,3]
which I know is not correct.
So your problem is in line #2. The numbers in the [] brackets are indices, which state which part of an array should be read. When the + operator is applied, they are not added, but instead the two
fib[2]
andfib[1]
are evaluated to their corresponding data, meaning they are evaluated to1
and1
, which then are added together to2
.I hope this is understandable. If not, just ask in the comments.
Well, why did you do this in your calculation
When you're dealing with arrays the value at the index represented by the sum of the indices is not equal to the sum of the values of the array at those indices.
To put it simply, you can't add the numbers within the square brackets on paper. Its like having two wallets with 5 and 15 dollars each in them. You can't say you have 15 dollars because 1+1 is two and you'll look into the second wallet. You'll add the 'contents' of the wallets instead to find the total monetary amount. Which is 20
You're code is fine. Ran this and got the proper output:
Console: 0,1,1,2,3,5,8,13,21,34
You are adding the indexes up not the value in the array the index points to
So next iteration
When you are reasoning about the code, you make the jump from
fib[3] = fib[2] + fib[1]
tofib[3] = fib[3]
. This happens to be a transformation that results in a correct statement, but it is not how it works. This code is adding the value at index2
to the value at index1
. That is not the same as taking the value at index3
. The way this reasoning should work is as follows:You start with
fib = [0, 1]
. Then in the first iteration of the loop you havefib[2] = fib[1] + fib[0]
. This means that you add the value at index0
(which happens to be0
) to the value at index1
(which happens to be1
) to get the value that you put at the end of the array (1
). Then in the second iteration, you do a similar thing, adding the value at index1
(still1
) to the value at index2
(also1
) to get2
, which goes at the end of the array. This continues, and at each iteration you add together the last two values in the array to get the next value.In JavaScript, when using an array like
fib
,fib[i]
refers to thei
th value in this array, counting from0
. Sofib[0]
is the first element in the array,fib[1]
is the second element in the array, and so on.Implementation with
array reduce()
ES6: