Java Recursive Binomial Coeffecients using Linked Lists

1.1k views Asked by At

There is a challenge problem in my compsci UIL class to use tail recursion to get a list of binomial coefficients for a given number . I think I am pretty close but I am having a hard time with base cases.

Following is my Code :

 public static Cons binomial(int n) 
    {
        return binomialb(n, null, 1);

    }
public static Cons binomialb(int n, Cons last, int power)
{

    if(n == power || n < 0)
    {
        return cons(1, null);
    }   
    else if(last == null)
    {
        last = cons(1, cons(1, null));
        return binomialb(n-1, last, power);
    }
    else
    { 
        Cons lst = cons(1, null);
        while(rest(last)!=null)
        {
        lst = cons((Integer)first(last)+(Integer)first(rest(last)), lst);
            last = rest(last);
        }
        return binomialb(n-1,lst,power);
    }

}

Right now I just get a list of (1).....

1

There are 1 answers

0
Daniel Fischer On

Your recursive call is always binomialb(n-1,something,power), so the only things that change are the first parameter, n, and the list. Your initial call has power = 1, so that will remain forever so. Now your first condition is

if (n == power || n < 0) { 
    return cons(1,null);
}

If you call it with n > 1 initially, the calls become binomialb(n-k,...,1) for k = 1, ..., n-1. Finally the call is binomialb(1,lotsOfWastedWork,1) which will happily return cons(1,null). If you initially call it with n < 1, the n < 0 will make it return the same after at most one recursive call, n = 1 immediately returns cons(1,null).

Whenever last is not null in a call, you should use it.