Added fibonacci sequence as well as fibonacci nth, renamed functions accordingly (#36)

This commit is contained in:
Oliver Hepworth-Bell 2018-06-02 07:31:09 +01:00 committed by Oleksii Trekhleb
parent a63bc67cf4
commit d267d72524
4 changed files with 59 additions and 27 deletions

View File

@ -2,14 +2,13 @@ import fibonacci from '../fibonacci';
describe('fibonacci', () => {
it('should calculate fibonacci correctly', () => {
expect(fibonacci(1)).toBe(1);
expect(fibonacci(2)).toBe(1);
expect(fibonacci(3)).toBe(2);
expect(fibonacci(4)).toBe(3);
expect(fibonacci(5)).toBe(5);
expect(fibonacci(6)).toBe(8);
expect(fibonacci(7)).toBe(13);
expect(fibonacci(8)).toBe(21);
expect(fibonacci(20)).toBe(6765);
expect(fibonacci(1)).toEqual([1]);
expect(fibonacci(2)).toEqual([1, 1]);
expect(fibonacci(3)).toEqual([1, 1, 2]);
expect(fibonacci(4)).toEqual([1, 1, 2, 3]);
expect(fibonacci(5)).toEqual([1, 1, 2, 3, 5]);
expect(fibonacci(6)).toEqual([1, 1, 2, 3, 5, 8]);
expect(fibonacci(7)).toEqual([1, 1, 2, 3, 5, 8, 13]);
expect(fibonacci(8)).toEqual([1, 1, 2, 3, 5, 8, 13, 21]);
});
});

View File

@ -0,0 +1,15 @@
import fibonacciNth from '../fibonacciNth';
describe('fibonacciNth', () => {
it('should calculate fibonacci correctly', () => {
expect(fibonacciNth(1)).toBe(1);
expect(fibonacciNth(2)).toBe(1);
expect(fibonacciNth(3)).toBe(2);
expect(fibonacciNth(4)).toBe(3);
expect(fibonacciNth(5)).toBe(5);
expect(fibonacciNth(6)).toBe(8);
expect(fibonacciNth(7)).toBe(13);
expect(fibonacciNth(8)).toBe(21);
expect(fibonacciNth(20)).toBe(6765);
});
});

View File

@ -1,26 +1,24 @@
// Calculate fibonacci number at specific position using Dynamic Programming approach.
export default function fibonacci(numberPosition) {
if (numberPosition === 1) {
return 1;
// Return a fibonacci sequence as an array
export default function fibonacci(n) {
const fibSequence = [1];
let currentValue = 1;
let previousValue = 0;
if (n === 1) {
return fibSequence;
}
let iterationsCounter = numberPosition - 1;
// Calculated fibonacci number.
let fib = null;
// Previous fibonacci number.
let fibPrev = 1;
// Before previous fibonacci number.
let fibPrevPrev = 0;
let iterationsCounter = n - 1;
while (iterationsCounter) {
// Calculate current value using two previous ones.
fib = fibPrev + fibPrevPrev;
// Shift previous values.
fibPrevPrev = fibPrev;
fibPrev = fib;
currentValue += previousValue;
previousValue = (currentValue - previousValue);
fibSequence.push(currentValue);
iterationsCounter -= 1;
}
return fib;
return fibSequence;
}

View File

@ -0,0 +1,20 @@
// Calculate fibonacci number at specific position using Dynamic Programming approach.
export default function fibonacciNth(n) {
let currentValue = 1;
let previousValue = 0;
if (n === 1) {
return 1;
}
let iterationsCounter = n - 1;
while (iterationsCounter) {
currentValue += previousValue;
previousValue = (currentValue - previousValue);
iterationsCounter -= 1;
}
return currentValue;
}