Update fibonacci-array-generator.md
The fibonacci sequence being zero indexed as well as the arrays, I think we could just initialize an array with the passed length, fill it with zeroes and use the indexes for the first positions.
This commit is contained in:
committed by
GitHub
parent
836216242d
commit
aab7a8da22
@ -4,11 +4,13 @@ Create an empty array of the specific length, initializing the first two values
|
|||||||
Use `reduce()` to add values into the array, using the sum of the last two values, except for the first two.
|
Use `reduce()` to add values into the array, using the sum of the last two values, except for the first two.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const fibonacci = n =>
|
const fibonacci = n => {
|
||||||
Array.apply(null, [0,1].concat(Array(n-2))).reduce(
|
return Array(n)
|
||||||
(acc, val, i) => {
|
.fill(0)
|
||||||
acc.push( i>1 ? acc[i-1]+acc[i-2] : val);
|
.reduce((acc, val, i) => {
|
||||||
|
acc.push(i > 1 ? acc[i - 1] + acc[i - 2] : i);
|
||||||
return acc;
|
return acc;
|
||||||
},[]);
|
},[]);
|
||||||
|
}
|
||||||
// fibonacci(5) -> [0,1,1,2,3]
|
// fibonacci(5) -> [0,1,1,2,3]
|
||||||
```
|
```
|
||||||
|
|||||||
Reference in New Issue
Block a user