Skip to content

Instantly share code, notes, and snippets.

@jdvp
Created August 2, 2017 21:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdvp/e13424887733e1226abd7c11b2add071 to your computer and use it in GitHub Desktop.
Save jdvp/e13424887733e1226abd7c11b2add071 to your computer and use it in GitHub Desktop.
RxJava Fibonacci Sequence
public class Utils {
public static Observable<Integer> fibonacci(int f1, int f2) {
return Observable.range(1, 1).
repeat().
scan(new ArrayList<>(Arrays.asList(f1, f2)),
(list, tick) -> {
list.add(list.get(list.size() - 2) + list.get(list.size() - 1));
list.remove(0); //or else this becomes pretty memory inefficient eventually, right?
return list;
}
).map(list -> list.get(list.size() - 1));
}
}
@schneiderlin
Copy link

schneiderlin commented Jun 28, 2018

maybe instead of using ArrayList, Tuple will be more readable?

private static Observable<Integer> fibsStartFrom(int f1, int f2) {
        return Observable.just(true)
                .repeat()
                .scan(Tuple.create(f1, f2), (tuple, dummyTrue) -> Tuple.create(tuple.value2(), tuple.value1() + tuple.value2()))
                .map(Tuple2::value2);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment