Created
June 16, 2014 23:16
-
-
Save AndrewReitz/961078962bbd49b9e6b1 to your computer and use it in GitHub Desktop.
RxJava implementation of Fibonacci Number
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
public class Main { | |
public static void main(String[] args) { | |
rxFibN(20).subscribe(new Action1<Integer>() { | |
@Override public void call(Integer result) { | |
System.out.println(result); | |
} | |
}); | |
} | |
static Observable<Integer> rxFibN(final int n) { | |
return Observable.range(1, n) | |
.map(new Func1<Integer, Fib>() { | |
@Override public Fib call(Integer integer) { | |
return new Fib(0, 1); | |
} | |
}).reduce(new Func2<Fib, Fib, Fib>() { | |
@Override public Fib call(Fib fib, Fib fib2) { | |
return new Fib(fib.n2, fib.n1 + fib.n2); | |
} | |
}).map(new Func1<Fib, Integer>() { | |
@Override public Integer call(Fib fib) { | |
return fib.n2; | |
} | |
}); | |
} | |
static class Fib { | |
final int n1; | |
final int n2; | |
Fib(int n1, int n2) { | |
this.n1 = n1; | |
this.n2 = n2; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment