Can someone trace me through this using the values (1,1) - java

I have been given this on a mock programming exam and I am not too good with this type of thing, can someone explain to me how I would go through something like the following? change the values to the one in the question if you feel like it explains it better. It is the final else which is really throwing me off. Thank you for the help.
public int function( int a, int b)
{
if (a<=0){
return b;
}
else if (b<=0)
{
return function( a-2, 0);
}
else
{
return function (function (a-1, b-1), b-1);
}

I interpret your (1,1) as a = 1 and b = 1. That said:
a = 1 > 0, the enter condition is false, so the first branch is not taken:
if (a<=0)
We go on until the second branch. b = 1 > 0 the enter condition is false again, so we won't take this branch neither:
else if (b<=0)
eventually, we reach the else branch and we take it:
else
So we land in this line:
return function (function (a-1, b-1), b-1);
There is a recursion, here! First call is function (a-1, b-1), so we are calling function with a = 1 - 1 = 0 and b = 1 - 1 = 0. Let's start again as above:
a = 0, so we take the first branch:
if (a <= 0)
and we return b = 0.
Now, it's time for the second recursion. We have a = function(a - 1, b - 1) = 0 and b = 1 - 1 = 0. It's still a = 0 and b = 0, so the result will be 0 as above.
Finally, we return 0.

Alright, I will step through other values so you can learn how to do it yourself.
lets take the values 2,2 for example.
check the first if statement(if (a<=0)) to see if its valid
a=2 so replace a with the value 2
is 2 <= 0? Nope. Lets go to the next statement
else if (b<=0)
NOTE: else if is essentially a statement that it used if the previous if statement for fails.
b = 2 is 2<=0? Nope. ONTO THE NEXT ONE!
else handles everything that fails under the first if and all the proceeding else ifs
So just plug in the values.
a = 2 b = 2
return function (function (a-1, b-1), b-1);
-->
return function (function (2-1, 2-1), 2-1);
-> return function (function (1, 1), 1);
You can go two ways with this keep recurring down or logically think about it.
Now... lets start noticing a pattern here and look for a base case (usually used for recursive functions like these) so you notice return b on the first if statement will ALWAYS be the actual returning result in the end and all the other recurring will stem off that result, because that's the only real value you will return. Now we got that established
How can we get to that value? if statement a<=0 is the only way to get there. You start noticing the relationships.
input a <= b or a <= 0 output b
input a > 0 a > b output 0

Related

I Need an explanation about the next recursion (I'm a beginner)

I know that lowkey it does 1 + 2 + 3 + 4 = 10, but I want to know how exactly it does that
public class Main {
public static int sum(int n) {
if(n == 0) return 0;
return sum(n - 1) + n;
}
public static void main(String[] args) {
System.out.println(sum(4));
}//main
}//class
public static int sum(int n) {
if(n == 0) return 0;
return sum(n - 1) + n;
}
When you call sum(4), the compiler does the following steps:
sum(4) = sum(3) + 4, sum(3) then calls sum(int n) and go to next step
sum(3) = sum(2) + 3, sum(2) then calls sum(int n) and go to next step
sum(2) = sum(1) + 2, sum(1) then calls sum(int n) and go to next step
sum(1) = sum(0) + 1, sum(0) then calls sum(int n) and go to next step
sum(0) = 0, return the value and bring it to previous step.
Then with backtracking, the compiler brings the value of sum(0) to the formula sum(0) + 1, so the value of sum(1) is 1. And so on, finally we get sum(4) is 10.
The key to understanding how this recursion work is the ability to see what is happening at each recursive step. Consider a call sum(4):
return
sum(3) + 4
sum(2) + 3
sum(1) + 2
sum(0) + 1
return 0 in next recursive call
It should be clear how a sum of 10 is obtained for sum(4), and may generalize to any other input.
Okay so lets understand it :
you call the method from main method passing the argument as 4.
It goes to method , the very first thing it checks is called as base condition in recursion . Here base condition is if n == 0 return 0.
We skipped the base condition since n is not yet zero . we go to return sum(n-1)+n that is sum(4-1)+4 . So addition will not happen , because you made the recursive call again to sum method by decrementing the n value to n-1 , in this case it is 3.
You again entered the method with n =3, check the base condition which is not valid since 3 != 0 , so we go to return sum (n-1)+3 , which is sum(3-1)+3
Next recursive call where n = 2 , base condition is not valid 2!=0 , so we return sum(n-1)+2that is sum(2-1)+2.
Next call with n = 1 , base condition is not valid , we go to return sum(n-1)+1 that is sum(1-1)+1.
Next recursive call with n = 0 , so now base condition is met , means it is time to stop the recursion and keep going back to from where we came to get the desired result. So this time we returned 0.
Lets go back to step 6 , with 0 we got and compute the addition part of sum(1-1)+1 . You got sum(1-1) => sum(0) = . So sum(1-1)+1 will be equal to 0+1=1
One more step back with 1 as value to step 5 , where we have sum(2-1)+2 = sum(1)+2 , sum(1) you know , which is 1 , so we will return 1+2=3 from this recursive call.
One step back with value as 3 , to step 4 , sum(3-1)+3 = sum (2)+3 = 3+3 =6 .
Going one step back with 6 as value to step 3 , sum(4-1)+4 = sum(3)+4 = 6+4 = 10 . And that is where we started from . You got the result as 10.
Recursion itself is very easy to understand.
From a mathematical point of view, it is just a simple function call, such as your code:
public static int sum(int n) {
if(n == 0) return 0;
return sum(n - 1) + n;
}
/*
sum(0) = 0
sum(1) = 1
sum(n) = n + sum(n-1)
*/
In fact, the concept of recursion has been introduced in high school. It is the "mathematical construction method" that is often used to prove sequence problems. The characteristics are obvious: the structure is simple and the proof is crude. As long as you build the framework, you can prove it in conclusion. So what is a recursive "simple structure" framework?
Initial conditions: sum(0) = 0
Recursive expression: sum(n) = sum(n-1) + n
And in fact about the sum() function, every calculation starts from sum(0), and it is natural. Even if you are asked to calculate sum(1000), all you need is paper, pen, and time, so recursion itself is not difficult.
So why recursion give people an incomprehensible impression? That's because "recursive realization" is difficult to understand, especially using computer language to realize recursion. Because the realization is the reverse, not to let you push from the initial conditions, but to push back to the initial conditions, and the initial conditions become the exit conditions.
In order to be able to reverse the calculation, the computer must use the stack to store the data generated during the entire recursion process, so writing recursion will encounter stack overflow problems. In order to achieve recursion, the human brain has to simulate the entire recursive process. Unfortunately, the human brain has limited storage, and two-parameter three-layer recursion can basically make you overflow.
Therefore, the most direct way is to use paper to record the stacks in your head. It is very mechanically painful and takes patience, but problems can often be found in the process.
Or, go back to the definition of recursion itself.
First write the architecture and then fill it in. Define the exit conditions and define the expression.
Second implement the code strictly according to the architecture. Recursive code is generally simple enough, so it is not easy to make mistakes in implementation. Once there is a problem with the program result, the first should not be to check the code, but to check your own definition.
Meeting Infinite loop? The initial conditions are wrong or missing; wrong result? There is a problem with recursion. Find out the problem, and then change the code according to the new architecture. Don't implement it without clearly defining the problem.
Of course, it really doesn't work. There is only one last resort: paper and pen.

Recursion gives unexpected/wrong output?

So I was doing a recursion challenge on codingbat and came across the "bunny ears" problem where we have a number of bunnies and each bunny has two big floppy ears. We want to compute the total number of ears across all the bunnies recursively (without loops or multiplication).
The solution apparently is quite simple:
public int bunnyEars(int bunnies)
{
if(bunnies == 0)
return 0;
return 2+bunnyEars(bunnies-1);
}
But I am not able to understand. If we pass 2 in the bunnyEars(2) method the
recursive part bunnyEars(bunnies-1); should have 1 left in the bracket after subtraction and thus 2+(1); which should be equal to 3 and not 4.
But the output comes as 4. So how does recursion actually work in this code?
It is not 2+(1), it is 2+numberOfEarsOfBunnies(1) == 2+2.
I renamed the function a little to make it more obvious.
Or even more into detail:
numberOfEarsOfBunnies(2)==
2+numberOfEarsOfBunnies(1)==
2+(2+numberOfEarsOfBunnies(0))==
2+(2+0)==
2+2==
4
if we pass 2 in the bunnyEars(2) method the recursive part bunnyEars(bunnies-1); should have 1 left in the bracket after subtraction and thus 2+(1); should be equal to 3 and not 4.
It seems you're misreading the expression. The line of code in question says
return 2+bunnyEars(bunnies-1);
Now you call bunnyEars(2), so bunnies == 2; and then you reach this line of code.
return 2+bunnyEars(bunnies-1);
resolves to
return 2+bunnyEars(2-1);
or
return 2+bunnyEars(1);
So a second instance of the bunnyEars() function starts running, with bunnies == 1. It reaches that same line of code, and this time
return 2+bunnyEars(bunnies-1);
is
return 2+bunnyEars(1-1);
or
return 2+bunnyEars(0);
So a third instance of bunnyEars() gets running, with bunnies == 0; but this matches your base case, so you just return 0 ; this time we don't recurse. So back up a level we find that
return 2+bunnyEars(0);
is
return 2+0; // because bunnyEars(0) returned 0
so that instance returns 2. And that means
return 2+bunnyEars(1);
becomes
return 2+2; // because bunnyEars(1) returned 2
And of course 2+2 is 4, the correct answer.
It seems as though you applied the -1 to the return value of the recursive bunnyEars() call, but the code says to apply it to the parameter you're sending in, not to the return value.

Recursion confusion with multiple return

I'm still wrapping my mind around recursion, and I think I get basic ones like factorial. But I'd like further clarification when the return statement is a little more complex like on the following snippet:
/**
* #param n >= 0
* #return the nth Fibonacci number
*/
public static int fibonacci(int n) {
if (n == 0 || n == 1) {
return 1; // base cases
} else {
return fibonacci(n-1) + fibonacci(n-2); // recursive step
}
}
In the return statement, does the fibonacci(n-1) completely recur through, before going down the fibonacci(n-2) step (does that make sense)? If so, this seems very difficult to envision.
Yes, one invocation will recurse all the way down and return, before the other one starts executing.
The order of invocation in Java is well-defined: fibonacci(n-1) goes before fibonacci(n-2).
Edit: Since the question originally included [C++] tag, here is the C++ part of the story: one of the two invocations still has to complete before the other one starts to run, but which one, fibonacci(n-1) or fibonacci(n-2), is unspecified.
Since the function has no side effects, it does not matter which of the two invocations gets to run first. The only thing that is important for understanding of recursion is that both invocations must complete, and their results must be added together, before the invocation at the current level returns.
It isn't much more different than calling a different function than itself. It needs to finish before the calling function can do anything with the result.
finobacci(0); // ==> 1 (since n is zero, the base case is to return 1)
fibonacci(1); // ==> 1 (since n is one, the base case is to return 1)
Now lets try 2 which is not the base case:
fibonacci(2); // == (since it's not the base case)
fibonacci(1) + fibonacci(0); // == (both calls to fibonacci we already haver done above)
1 + 1 // ==> 2
So in reality what happens is that the call to fibonacci2 waits while each of the two recursive calls to finish, just like a function that does System.out.println would wait until it had printed the argument before continuing to the next line. Recursion isn't that special.
Trivia: This is the original series from Fibonacci himself. Modern mathematicians start the series with n as the base case result making the series 0, 1, 1, 2, ... rather than 1, 1, 2, 3, ....
it works in this way:
Fibonacci program:
public int fibonacci(int n) {
if(n == 0)
return 0;
else if(n == 1)
return 1;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
Explanation:
In fibonacci sequence each item is the sum of the previous two. So, as per recursive algorithm.
So,
fibonacci(5) = fibonacci(4) + fibonacci(3)
fibonacci(3) = fibonacci(2) + fibonacci(1)
fibonacci(4) = fibonacci(3) + fibonacci(2)
fibonacci(2) = fibonacci(1) + fibonacci(0)
Now you already know fibonacci(1)==1 and fibonacci(0) == 0. So, you can subsequently calculate the other values.
Now,
fibonacci(2) = 1+0 = 1
fibonacci(3) = 1+1 = 2
fibonacci(4) = 2+1 = 3
fibonacci(5) = 3+2 = 5
In multiple recursion the program calls itself with its first call until the base case is reached, in this case fibonacci(n-1); after that the recursion stops and return his value to continue calling the value to the second part of the recursion fibonacci(n-2).
If you don't visualize the multiple recursion in the program, this
fibonacci recursion tree may be helpful.

Need help solving Java recursive

I been trying to figure out how to solve this question but I do not understand. If i take mystery(2,25), b is not ==0 and b%2=1 so then I have mystery(2+2, 25/2) + 2. I dont understand what I do with the +2 in the end and I dont understand if I am supposed to add a and b or to do the code again with the new values.
What are the values for mystery(2, 25) and mystery(3, 11) respectively?
public static int mystery(int a, int b) {
if (b == 0) return 0;
if (b % 2 == 0) return mystery(a+a, b/2);
return mystery(a+a, b/2) + a;
}
Answer to choose from:
33554432, 177147
525, 1331
50, 33
75, 44
I create an image trying to illustrate the answer...
-About the +2 you have to add after the return of the next call back...
Note: If you pass a float value to int parameter as 12.5 the parameter will get only the integer part: 12
If it is ok, please check as correctly! ;)
Evaluate each call to mystery until b is 0 and the recursive call chain terminates. You then add the final 0 result with the intermediate a (the +a) in the code.

Gate XOR logic in java

folks... the XOR Gate is still giving me a hard time. I'm really close to finishing it but some of the test cases are failing. My specs say that if I have more than two of 1 (High Signals) such as:
111100 or 111 or 11 or 00 or 0000 so the output should be 0 (Low Signal).
Else if any input signal is 'X' the output is also X such as
XX00111 or XX10 or 0X01 then the output should also be X
Else if all the input signals are known (no X signals) and there is EXACTLY one 1 signal then the output is 1 such as
000001 or 10000 or 01 or 10 then the output should be 1
Note: All of the getters and setter methods are correct (tested) and Signal.HI ==1, Signal.LO = 0 and Signal.X = X.
Could smb help me with this method? When the inputs signals are 011 the output should be 0 when Im getting 1. Secondly, when the inputs are XX Im getting 0 when it should be X. Could smb please hint me or help me? Thanks in advance!
#Override
public boolean propagate()
{
Signal inputSignal;
int countHI = 0;
List<Wire> inputs = getInputs();
Signal temp = getOutput().getSignal();
for(int i = 0; i < inputs.size(); i++)
{
inputSignal = inputs.get(i).getSignal();
if(inputSignal == Signal.X)
{
getOutput().setSignal(Signal.X);
break;
}
else if(inputSignal == Signal.HI)
countHI++;
else if(inputSignal == Signal.LO)
getOutput().setSignal(Signal.HI);
}
if(countHI > 2 || countHI == 0)
getOutput().setSignal(Signal.LO);
....................................further unnecessary code for this problem
Here is what is happening:
When you are detecting an input signal of X, you are setting the output as X, and breaking out of the loop... but the last IF statement is still being executed, and so because your input is 'XX', countHI is zero, and so the last if condition is satisfied and you end up overriding the output signal by setting it to 0 at the end of your code. The break only breaks out of the loop it is currently in.
Your code only checks if hiCount is greater than 2 in the last if statement, but you expect it to be false when there are two or more 1's, so when you have exactly two 1's, you do not enter that if condition.
You need to think about your solution logically and run through it yourself and then you will realize why it is not working as you expect.
Here's how I would code it. Note that I only set the signal when I'm sure that it's the correct value: after the loop.
Also note that I make all the cases mutually exclusive.
boolean hasX = false;
boolean hiCount = 0;
for (Wire wire : inputs) {
Signal inputSignal = wire.getSignal();
if (inputSignal == Signal.X) {
hasX = true;
// optimization: break out of the loop early since we know
// that, whatever the number of HI and LO, if there is one
// X, the result is X
break;
}
else if (inputSignal == Signal.HI)
hiCount++;
}
}
if (hasX) {
getOutput().setSignal(Signal.X);
}
else if (hiCount == 1) {
getOutput().setSignal(Signal.HI);
}
else {
getOutput().setSignal(Signal.LO);
}

Categories

Resources