Created
August 11, 2017 08:35
-
-
Save rcgonzalezf/e30f8e693bf044e8b6b80f8c05d4ac12 to your computer and use it in GitHub Desktop.
Trying to achieve pure functions with Kotlin.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.rcgonzalezf.onetoten | |
import java.math.BigInteger | |
/** | |
* | |
* https://projecteuler.net/problem=2 | |
* | |
* 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. | |
* | |
*/ | |
class Problem2 { | |
val fibonacciValues = hashMapOf<Int, BigInteger>(0 to BigInteger.ONE, 1 to BigInteger.ONE); | |
fun solve(fibonacci: Int, maxValue: Int = 4000000): BigInteger { | |
calculateFibonacci(fibonacci) | |
return fibonacciValues.filter { | |
it.value < BigInteger.valueOf(maxValue.toLong()) && | |
it.value.mod(BigInteger.ONE.add(BigInteger.ONE)).equals(BigInteger.ZERO) | |
}.values.fold(BigInteger.ZERO, BigInteger::add) | |
} | |
// * TODO investigate how to do dynamic programming with a pure function ** // | |
private fun calculateFibonacci(n: Int): BigInteger? { | |
if (fibonacciValues.contains(n)) { | |
return fibonacciValues.get(n) | |
} else { | |
val f = calculateFibonacci(n - 2)!!.add(calculateFibonacci(n - 1)) | |
fibonacciValues.put(n, f) | |
return f | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This was the end result: