Created
September 12, 2015 11:12
-
-
Save shout-poor/7bc5ca7f774ece9352a4 to your computer and use it in GitHub Desktop.
Java8のStreamAPIでフィボナッチ関数
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
import java.math.BigInteger; | |
import java.util.function.UnaryOperator; | |
import java.util.stream.Stream; | |
import static java.math.BigInteger.*; | |
public class Fibonacci implements UnaryOperator<BigInteger> { | |
@Override | |
public BigInteger apply(BigInteger n) { | |
assert(n != null && n.compareTo(ZERO) >= 0); | |
return Stream.iterate(new BigInteger[] { ZERO, ZERO, ZERO }, cont -> { | |
BigInteger x = cont[0].add(ONE); | |
BigInteger preY = cont[1]; | |
BigInteger y = (x.equals(ZERO)||x.equals(ONE)) ? x : cont[1].add(cont[2]); | |
return new BigInteger[] {x, y, preY}; | |
}) | |
.filter(cont -> cont[0].equals(n)) | |
.findFirst() | |
.map(cont -> cont[1]) | |
.orElseThrow(() -> new RuntimeException("Failed.")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment