Last active
August 29, 2015 14:20
-
-
Save shekhargulati/1b6f18bb29f23b18dd0d to your computer and use it in GitHub Desktop.
Reactive Collatz Conjecture Sequence
This file contains hidden or 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 rx.Observable; | |
| import rx.Subscriber; | |
| import java.util.stream.IntStream; | |
| public class CollatzConjectureSequence { | |
| public static void main(String[] args) { | |
| Observable<Integer> observable = CollatzConjectureSequence.create(19); | |
| observable.doOnNext(val -> { | |
| try { | |
| Thread.sleep(500); | |
| } catch (InterruptedException e) { | |
| } | |
| }).subscribe(val -> System.out.println(IntStream.rangeClosed(1, val).mapToObj(number -> String.valueOf(number)).reduce("", (acc, number) -> acc + "*"))); | |
| } | |
| private static Observable<Integer> create(final int n) { | |
| return Observable.<Integer>create(subscriber -> { | |
| subscriber.onNext(n); | |
| sequence(subscriber, n); | |
| }); | |
| } | |
| private static void sequence(Subscriber<? super Integer> subscriber, int number) { | |
| if (number == 1) { | |
| subscriber.onCompleted(); | |
| } else if (number % 2 == 0) { | |
| int next = number / 2; | |
| subscriber.onNext(next); | |
| sequence(subscriber, next); | |
| } else { | |
| int next = number * 3 + 1; | |
| subscriber.onNext(next); | |
| sequence(subscriber, next); | |
| } | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For n = 19 it produces following