Skip to Content
author's profile photo Frank Schuler

CCC2 Solving the Longest Collatz sequence problem with SAP Data Intelligence

Former SAP Data Hub, now SAP Data Intelligence, offers the option to develop custom Java Script Operators. Therefore I decided to implement the SAP Community Coding Challenge Nr.2 with this Graph:

Controller: Generates numbers from 1 to a set limit, detects the next longest sequence and outputs it to the Wiretap:

var counter = 1;
var longest = 0;
var sequence = 0;

$.addGenerator(gen);

$.setPortCallback("input",onInput);

function gen() {
    $.output(counter);
}

function onInput(ctx,n) {
    if (n > sequence) {
        longest = counter;
        sequence = n;
        $.debug(longest.toString() + " " + sequence.toString());
    }
    if (++counter > $.config.getInt("limit")) {
        $.stop(null);
    } else {
        $.output(counter);
    }
}

Sequencer: Detects the end of a sequence and starts the next one:

sequence = 0;

$.setPortCallback("input",onInput);

$.setPortCallback("odd",onOdd);

function onInput(ctx,n) {
    sequence++;
    if (n > 1) {
        $.loop(n);
    } else {
        $.next(sequence);
        sequence = 0;
    }
}

function onOdd(ctx,n) {
    sequence++;
    $.even(n);
}

Splitter: Distinguishes between even and odd numbers:

$.setPortCallback("input",onInput);

function onInput(ctx,n) {
    if (n % 2) {
        $.odd(n);
    } else {
        $.even(n);
    }
}

Even: Processes even numbers:

$.setPortCallback("input",onInput);

function onInput(ctx,n) {
    $.output(n / 2);
}

Odd: Processes odd numbers:

$.setPortCallback("input",onInput);

function onInput(ctx,n) {
    $.output(3 * n + 1);
}

As a result, I get every next Longest Collatz sequence up to the limit I set in the Controller displayed in my Wiretap:

* Please Login or Register to Comment on or Follow discussions.

0 Comments

    Add a comment
    10|10000 characters needed characters exceeded