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).....
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 haspower = 1
, so that will remain forever so. Now your first condition isIf you call it with
n > 1
initially, the calls becomebinomialb(n-k,...,1)
fork = 1, ..., n-1
. Finally the call isbinomialb(1,lotsOfWastedWork,1)
which will happily returncons(1,null)
. If you initially call it withn < 1
, then < 0
will make it return the same after at most one recursive call,n = 1
immediately returnscons(1,null)
.Whenever
last
is not null in a call, you should use it.