Project Euler (FP) - Problem 2
The Problem
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
A Solution
Problem 1 also asked for a generated number set less than a given number so today I realized that could be abstracted. Here’s what I came up with:
function setLessThan(nextInSet, first) {
return function setGenerator(bound) {
var set = [];
var next = first;
var lastIndex = 0;
while(next < bound) {
set.push(next);
next = nextInSet(set, lastIndex);
lastIndex++;
}
return set;
}
}
setLessThan
consumes a function that returns the next number in a set given the set and the last index position along with the first number in the sequence. Of course, the last index could be found from the set and maybe that’s the wiser option, but I decided to calculate the last index in the set generator to be less computationally expensive.
Two examples of functions that find the next number in a sequence:
function nextFibonacciSequence(set, lastIndex) {
return set[lastIndex] + (set[lastIndex - 1] || 1);
}
function nextMultiple(multiplier) {
return function innerNextMultiple(set, lastIndex) {
return set[lastIndex] + multiplier;
}
}
Generate the set:
var fibonacciLessThan = setLessThan(nextFibonacciSequence, 1);
var fibSet = fibonacciLessThan(4000000); // Four million
Then reuse some utilities from the first problem:
var evens = filter(multipleOf(2));
var evenFibSet = evens(fibSet)
var fibSum = addUp(evenFibSet);
console.log('fibSum', fibSum); // 4613732
Conclusion
I like this functional programming thing! After only two problems, I can see how FP is pushing me in the direction of much more reusable programming.
And I haven’t even got to the good parts like currying or partial application of parameters and all the other things I’m sure I have no clue about.