Home » Java » java – Finding the nth value of the Recaman sequence using a lambda expression-Exceptionshub

java – Finding the nth value of the Recaman sequence using a lambda expression-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am studying the stream API and I have some questions. I will be very grateful if you can help.
My code 1:

public long recaman(long n) {
    HashSet<Long> s = new HashSet<>();
    s.add(0L);
    long prev = 0;
    for (int i = 1; i < n; i++) {
        long curr = prev - i;
        if (curr < 0 || s.contains(curr)) {
            curr = prev + i;
        }
        s.add(curr);
        prev = curr;
    }
    return prev;
}

My code 2:

public int recaman(int n) {
    int[] seq = new int[n];
    boolean[] check = new boolean[10 * n];

    seq[0] = 0;
    check[0] = true;
    for (int k = 1; k < n; k++)
    {
        int minusVal = seq[k - 1] - k;
        int plusVal = seq[k - 1] + k;
        if ((minusVal > 0) && (!check[minusVal]))
        {
            seq[k] = minusVal;
            check[minusVal] = true;
        } else
        {
            seq[k] = plusVal;
            check[plusVal] = true;
        }
    }
    return seq[n - 1];   
}

How do I rewrite the code using a lambda expression (or use functional programming paradigm)?

How to&Answers:

In both functions you are iterating over an int variable (i in the first one, k in the second)

Your loops use the iteration variable explicitly (in long curr = prev - i; and in int minusVal = seq[k - 1] - k;). As such it is not a “pure” iteration variable anymore, but it’s both an iteration variable and data.

One of the goals of Streams is to abstract iteration, and do away with iteration variables. In a lambda function, the position of an element in the stream is not available. Thus, what you ask for is impossible with the Java Stream API.

If you still want to use functional programming paradigm to solve this problem, you should use recursion (ie. Streams are not the right tool for your job, recursion is).