Program flow on recursion with strings and ints - java

I don't understand how this works. I know basic factoral recursion, but this is of a mixed type. Could someone explain step by step on what's going on with the output based on this exact code snippet? Even just a few of the first values (commented at the end of the code)?
Thanks :)
public class recursion1st
{
public static String recFun(int x)
{
if (x <= 0) return "/";
return recFun(x-3) + x + recFun(x-2) + x;
}
public static void main(String[] args)
{
System.out.println(recFun(8));
}
}
//Produces '/2/25/3/1/1358/3/1/136/1/14/2/2468 '(?)

3| function taking an int argument
5| this is your base case, return "/" if...
6| this is your recursion, call recFun(x-3) + x /*this is your current value */ recFun(x-2) + x. basically this is going to go until you're x reaches 0 or less. Note the right root recursive call will go through more recursions before it hits the base case because it is passing x - 2 everytime instead of x-3. Also realize this statement calls recursively twice.
Make a chart on a big piece of paper and map out passing 8 in:
8
root
return recFun(5) + 8 + recFun(6) + 8
1st branch
return recFun(2) + 5 + recFun(3) + 8
2nd branch
return recFun(3) + 6 + recFun(4) + 6
.......................
Keep going it will become clear.

In the main function, it is calling recFun() to print the data. In that function, which is recursive, the first if condition is to break out of recursion, when that condition is met (when x is negative or equal to zero).
Else it will return a string, in turn again calling itself.
Here, in the first return, it calls recFun(5) and and recFun(6) and likewise, if you analyse step by step, the cycle continues till the break condition is met. Basically the return statement is concatenation of strings, and it separates the data by placing "/" on breaking out of recursion.
EDIT:
Value returned by return statement is
rec(5)+8+rec(6)+8......(1)
where
rec(5) returns rec(2)+5+rec(3)+5......(2)
and
rec(6) returns rec(3)+6+rec(4)+6.......(3)
where
rec(3) returns "/"+3+rec(1)+3.......(4)
and
rec(4) returns rec(1)+4+rec(2)+4.....(5)
and
rec(2) returns "/" +2 +"/"+2.....(6)
and
rec(1) returns "/"+1+"/"+1 .......(7)
Substitute (7) and (6) in (5)
Substitute (7) in (4)
Substitute (4) and (5) in (3)
Substitute (4) and (6) in (2)
and substitute (2) and (3) in (1)
You will need a sheet for this. Try and work it out using this. Hope it helps. :)

take a paper and write down step by step what the function does:
recFun(5)
|
recFun(2) + 5 + recFun(3)+5
| |
recFun(-1)+2+recFun(0)+2 recFun(0)+3+recFun(1)+3
| | | |
"/" "/" "/" recFun(-2)+1+recFun(-1)+1
| |
"/" "/"
1 call recFun with 5
2 5 leads to recFun with 2 & recFun with 3
3 2 leads to recFun with -1 & recFun with 0 , 3 leads to recFun with 0 & recFun with 1
4 -1 leads to "/", 0 leads to "/", 0 leads to "/", 1 leads to recFun with -2 & recFun(-1)
5 -2 leads to "/", -1 leads to "/"
Until every singe call is finished executing (until the x <= 0 and a "/" is returned) no call made before will return anything. The function starts returning Strings from the end of that chain of calls (in this pyramid: bottom to top and from right to left)
/ 1 / 1
/ 2 / 2 / 3 3
5 5
-> / 2 / 2 5 / 3 / 1 / 1 3 5
I know, recursion is confusing. The only thing that helps me is: first make every last call of the recursive function and only when the last call returns anything then roll back. Sorry if this isn't any more precise :)

Related

Trouble following recursive code

Just trying to understand how this code works. Say the integer is 4, I understand that 4 is checked against the base case and then the method calls itself again this time with the integer 3 and then same pattern occurs until the integer is 1. My question is how is the summation part being done? What would be the final result?
public int sum(int num)
{
int result;
if (num == 1)
result = 1;
else
result = num + sum(num-1);
return result;
}
As I think you realize based on your post, the magic happens here: result = num + sum(num-1); Think of it as a chain of method calls. Logically, the whole process could be represented like this:
sum(4);
evaluates to
4 + sum(3);
which evaluates to
4 + 3 + sum(2);
which evaluates to
4 + 3 + 2 + sum(1);
which evaluates to
4 + 3 + 2 + 1
which is equal to
10
The summation happens as the recursive calls return back up the stack. See here:
sum(4) # The initial function call
|
|---------------|
| 4 + sum(4-1) | # num + recursive call
|
|---------------|
| 3 + sum(3-1) | # the next num + the next recursive call
|
|---------------|
| 2 + sum(2-1) |
|
|---|
| 1 | # Base case num == 1
If you populate each recursive sum(...) call with the value below it, what do you get? The sums added up. That's where the addition occurs.
Trace this and find out what the value should be for yourself. Or, run the code.
It happens here:
result = num + sum(num-1);
together with
return result;
Iteration n calls sum() again (triggering iteration n+1). The result of n+1 is returned; and added to n; giving the result of n-1 (because of the later return statement).
And for the record: I did not include the final solution in my answer; as you can figure that easily by yourself; either by running that code; or by using a pen and a piece of paper to "run" this code "manually".

Java Recursion Total Breakdown

ArithmSumRec(n)
1. If n = 1
1.1 return 1
2. Else
2.1 return ArithmSumRec(n-1) + n
So for example we want to calculate when n = 5. it will look something like this.
Executing ArithmSumRec(5) ⇒ 5 calls to ArithmSumRec(...)
ArithmSumRec(5)
ArithmSumRec(4)
ArithmSumRec(3)
ArithmSumRec(2)
ArithmSumRec(1)
return 1 // base case
return 1 + 2 (= 3)
return 3 + 3 (= 6)
return 6 + 4 (= 10)
return 10 + 5 (= 15)
But my question is now, when the method returns the first time it's:
return ArithmSumRec(5-1) + 5;
But what happens to that 5 that's outside the parentheses. Why doesn't the method return 9 (since (5-1)+5 = 9?) and instead it returns a 4? And where does that +n go?
And if there's a good thread already that I haven't found or website that thoroughly explains recursive methods, I would appreciate that a lot.
This is order of operations. A function call takes precedence over addition. Thus, when you call
func(5-1) + 5
... the first operation is 5-1, giving 4. Now the run-time system executes the call func(4). After this is done, it finally adds the 5.
Compare your situation with a different function call:
sqrt(5-1) + 5
This is equivalent to having the square root sign over "5-1" with a "+ 5" after all of that. This simplifies to sqrt(4) + 5, or 7. It does not evaluate to 9 (following your original statement as written), nor does it evaluate to 3 (from sqrt(5-1 + 5)).
Does that help?
Recursive calls do not return anything until you stop the recursion. If there wouldn't be the
if (n==1) return 1;
the program would hang there.
But when you hit the return 1, then the whole calculation is clear and you can actually return a number:
5 + 4 + 3 + 2 + 1 = 15

How are the numbers stored, called, and added in this short recursion example?

First off, it's not homework. I'm practicing examples from http://codingbat.com/java/Recursion-1. Every time I think I'm beginning to understand recursion, I run into a problem that makes me realize I have no idea, and the only thing tutors or internet explanations ever say is that "the function calls itself until the base case is met."
public int sumDigits(int n) {
if(n < 10) {
return n;
} else return sumDigits(n/10) + n % 10;
}
If I pass 115 to this on my computer, the output is 7 (as it should), but I don't understand how the program comes to this conclusion. Here is how I see it:
115 is not less than 10, so return the program with 115/10 (which is 11). 11 is not less than 10, so return the program with 11/10 (which is 1). Add this to 115%10 (which is 5). So how does this program get 7???
It seems like no matter how many examples I look at, I cannot find a pattern in how this works.
You may find it easier to reason about this code if you swap the two operands of the +, that is, change it to read:
return (n % 10) + sumDigits(n / 10)
i.e.
sumDigits(115) = 5 + sumDigits(11)
sumDigits(11) = 1 + sumDigits(1)
sumDigits(1) = 1
so expanding that:
sumDigits(115) = 5 + (1 + sumDigits(1))
= 5 + 1 + 1
= 7
Here is how it happens explained with a diagram
You have it almost correct, you just missed one step when returning out of the recursion - when returning from the 11/10, you add another 1:
call for 115
115 > 10, call recursively for 11
11 > 10, call recursively for 1
1 < 10, return 1
return the 1 from recursive invocation + 11%10 = 1 + 1 = 2
return the 2 from recursive invocation + 115%10 = 2 + 5 = 7

eli5 can't understand this recursion process

public int recursive(int x){
if(x>10){
return x;
}
int y = x + 1;
int r = recursive(y);
System.out.println(y + " Y" + " R" + r + " X " + x);
return r;
}
public static void main(String[] args) {
System.out.println(new a().recursive(1));
}
This is a recursion I made to simplify a different method I could not understand but it has the same code line for line basically. I don't understand what is happening on this line int r = recursive(y);. I don't understand what the return r; even returns to or how it actively loops. When I system print R, it is always the same value each iteration which throws me off. If I change return r to return 555 the code still works but just returns 555 to the call from main.
output
11 Y R11 X 10
10 Y R11 X 9
9 Y R11 X 8
8 Y R11 X 7
7 Y R11 X 6
6 Y R11 X 5
5 Y R11 X 4
4 Y R11 X 3
3 Y R11 X 2
2 Y R11 X 1
11
Please eli5, I have viewed some recursion videos but they do not use a recursion thats laid out like this, with a return after a recursive call. int r = recursive(y);, how does r get its value here, and continue the loop, can't figure it out. It says set r equal to the return of recursive(y), but the return is r itself when the value for r has not been set or something?
Another issue I am having is how the system print is running as well, because I thought when the recursive part runs, it instantly restarts the method but it seems the entire method is running and looping
My friend it looks to me that your recursion breaking conditions is at r>10 so it always breaks at 11 thats the only cause............
suppose you have pass x=1
then your recursive(1) calls recursive(2), recursive(2) calls recursive(3), recursive(3) calls recursive(4) , recursive(4) calls recursive(5) , recursive(5) calls recursive(6), recursive(6) calls recursive(7), recursive(7) calls recursive(8), recursive(8) calls recursive(9), recursive(9) calls recursive(10), recursive(10) calls recursive(11)
and then recursion breaks and at recursive(11) it returns you 11 at this line `int r = recursive(y); so r becomes 11 and then recursion(10) returns you r and then recursion(9) returns you are and so on ................. for whole stack
You can think of it like a simple loop in this case, it just iterates untill x is > 10, so ret value of this recusrsion is 11, since it is the first number which is bigger than 10. Since nothing printed before recursive call you print the values in the reversed order, after x becomes 11, and function returns, previos stack frame contains values x == 10, y 10 + 1, and r contains return value of the functon => 11, same for previos frame and previos .....
When you enter 555, the first condition you have in your function is to return the value if it is greater than 10, so as 555 is greater than 10, it returns directly the value (555).
Now, for the recursion. It's pretty simple, just imagine how the code flows, you enter 1 as a parameter, is it greater than 10? No, so we move to the next line. We assign y the value of x plus 1, so X=1, and Y=2.
And then instead of returning a value, we call again the same function, but instead of 1 as a parameter, we call it with 2 as a parameter (the value of Y). And we start again (that's the point of recursion), but now X=2: Is 2 greater than 10? Now, so we move to the next line. We assign Y the value of the parameter (which is called X) plus 1, so now Y=3 and X=2. Remember that the variables' scope are only in the same function they are declared.
Repeat this, until the parameter goes above 10 (by adding one each time you call the recursive function), and then finally it returns a value! (in the condition where x > 10), so the function finishes and returns the value to the function who called it, which happens to assign that value to R and prints the result.
And so on, finishing each of the called functions that had different values as a parameter (1, 2, 3, etc until 10, as the function each time added one to the parameter and called itself).
I hope this helped you to understand it better, I'm not sure how to explain this simplier. I guess a 5 year old would have some problems to understand this :)

A mathematical function that gets us the number of leaves of a specific type of k-ary?

I am trying to figure out a function f(x) that would calculate the number of leaves in a k-ary tree. For example, assume we created a tree that began with root 4 with 3 children, each of -1,-2,-3 respectively. Our leaves would only be 0 values, not null values. I have spent the past day trying to figure out a function and it seems like nothing I do goes in the correct direction.
EX:
4
/ | \
3 2 1
/ |\ /| /
2 1 0 1 0 0
/| / /
1 0 0 0
/
0
7 Leaves.
Any help would be very much appreciated! Thanks!
To clarify, I need a mathematical equation that derives the same answer as code would if I recursively transversed the tree.
More examples:
{4,7}{5,13}{6,24}{7,44}{8,81}{9,149}{10,274}{11,504}{12,927}{13,1705}{14,3136}{15,5768}{16,10609}{17,19513}{18,35890}{19,66012}{20,121415}
public int numleaves(TreeNode node) {
if (node == null)
return 0;
else if (node.getLeft() == null && node.getMiddle() == null && node.getRight() == null)
return 1;
else
return numleaves(node.getLeft()) + numleaves(node.getMiddle()) + numleaves(node.getRight());
}
I cannot answer your question, but it has a solution. I can only outline the case for the number of children k being equal to 2. The case k=3 leads to a cubic polynomial with two complex and one real solution, I lack the tools here to derive them in a non-numerical way.
But let's have a look at the case k=2. Interestingly, this problem is very closely related to the Fibonacci numbers, except for having different boundary conditions.
Writing down the recursive formula is easy:
a(n) = a(n-1) + a(n-2)
with boundary conditions a(1)=1 and a(0)=1. The characteristic polynomial of this is
x^2 = x + 1
with the solutions x1 = 1/2 + sqrt(5)/2 and x2 = 1/2 - sqrt(5)/2. It means that
a(n) = u*x1^n + v*x2^n
for some u and v is the explicit formula for the sequence we're looking for. Putting in the boundary conditions we get
u = (sqrt(5)+1)/(2*sqrt(5))
v = (sqrt(5)-1)/(2*sqrt(5))
i.e.
a(n) = (sqrt(5)+1)/(2*sqrt(5))*(1/2 + sqrt(5)/2)^n + (sqrt(5)-1)/(2*sqrt(5))*(1/2 - sqrt(5)/2)^n
for k=2.
Your code seems to be computing a Tribonacci sequence with starting values 1, 1 and 2. This is sequence A000073 from the On-Line Encyclopedia of Integer Sequences, starting from the third entry of that sequence rather than the first. The comments section of the encyclopedia page gives an explicit formula: since this is a linear recurrence relation with a degree 3 characteristic polynomial, there's a closed form solution in terms of the roots of that polynomial. Here's a short piece of Python 2 code based on the given formula that produces the first few values. (See the edit below for a simplification.)
from math import sqrt
c = (1 + (19 - 3 * sqrt(33))**(1/3.) + (19 + 3 * sqrt(33))**(1/3.)) / 3.
m = (1 - c) / 2
p = sqrt(((3*c - 5)*(c+1)/4))
j = 1/((c-m)**2 + p**2)
b = (c - m) / (2 * p*((c - m)**2 + p**2))
k = complex(-j / 2, b)
r1 = complex(m, p)
def f(n):
return int(round(j*c**(n+2) + (2*k*r1**(n+2)).real))
for n in range(0, 21):
print n, f(n)
And the output:
0 1
1 1
2 2
3 4
4 7
5 13
6 24
7 44
8 81
9 149
10 274
11 504
12 927
13 1705
14 3136
15 5768
16 10609
17 19513
18 35890
19 66012
20 121415
EDIT: the above code is needlessly complicated. With the round operation, the second term in f(n) can be omitted (it converges to zero as n increases), and the formula for the first term can be simplified. Here's some simpler code that generates the same output.
s = (19 + 297**0.5)**(1/3.)
c = (1 + s + 4/s)/3
j = 3 - (2 + 1/c)/c
for n in range(0, 32):
print n, int(round(c**n / j))
I can't help it, but I see Binomial tree in it. http://en.wikipedia.org/wiki/Binomial_heap
I think that good approximation could be sum of k-th row of pascal triangle, where k stands for the number of the root node.
Isn't this easier to understand:
We set the starting values for the tribonacci sequence into a list called result. Then we put these values into 3 variables. We change the variable content based on the tribonacci formula (new a is a+b+c, new b is old a, new c is old b). Then we calculate to whatever tribonacci number we want to go up to and store each result into our result list. At the end, we read out the indexed list.
result=[1,1,2]
a,b,c=result[-1],result[-2],result[-3]
for i in range(40):
a,b,c=a+b+c,a,b
result.append(a)
for e,f in enumerate(result):
print e,f

Categories

Resources