How do I change two functions that are Mutual Recursive to each other to make them into a linear recursion? Do I have to have both the methods in a single method?
You should be able to simply "inline" the implementation of the second method, into the first method.
That is,
public static void methA() {
// snippet 1
methB();
// snippet 2
}
public static void methB() {
// snippet 3
methA();
// snippet 4
}
becomes
public static void methAB() {
// snippet 1
// snippet 3
methAB();
// snippet 2
// snippet 4
}
If the second method is long, and called from multiple points in the first method, it may get messy though.
Related
this is my code:
public class Player
2 public class PlayerUtility {
4 public Player findPlayerDetailsById(Player[] arr, int playerIdToSearch){
7 ..
18 return null;
2 public class Main {
3 public static void main(String[] args) {
...
12 PlayerUtility obj=new PlayerUtility();
..
18 System.out.println(obj.findPlayerDetailsById(pObj,id));
21 if(obj.findPlayerDetailsById(pObj,id)==null)
22 {
23 System.out.println("No player found");
It's giving the outputs as expected according to the test cases but there's one failed test case Fail 1 -
Check the return type of findPlayerDetailsById method in PlayerUtility class(or)the findPlayerDetailsById method returns the null value
what should i return instead?
First thing please remove return statement from main because main is of void type.
Second check whether array variable Obj is even initialized or not(or even you need to use Obj value which is not required)or you only need arr variable to complete operation
Third implement getPlayerName and getPhoneNumber method before calling them.
Fourth check this statement pObj.setPlayerId(id) it's incorrect because you cannot call method without using array index which will refer to an object.
Remove these basic error and edit problem with new issue you are facing if their is any
update:
i was able to get rid of the last error by returning the array and not an empty object.
Thank you for all the help!
I need to write a printBackwards() method, using three pre-given methods first, rest and length. printBackwards() method needs to take String as a parameter and prints each letter of that string on the console, but each letter needs to be printed on new line and in reverse order. So if the String is House, the output should be:
e
s
u
o
H
In this exercise, we should use recursion and if-else statements. No arrays, no other (familiar) String method, no while and for loop.
I have done a little bit, I know it is not correct, but that is how much I managed to do. I dont understand how to write code so the method can return letters before letter e. How to use recursion here ?
public class Recurse {
public static void main(String args[]){
System.out.println(printBackwards("House"));
}
//printBackward: takes a String as a parameter and prints letters of the String,
// one on each line, but backwards
public static String printBackwards(String s){
if (length(s) == 1){
return s;
} else {
return printBackwards(rest(s));
}
}
// first: returns the first character of the given String
public static char first(String s) {
return s.charAt(0);
}
// last: returns a new String that contains all but the
// first letter of the given String
public static String rest(String s) {
return s.substring(1, s.length());
}
// length: returns the length of the given String
public static int length(String s) {
return s.length();
}
}
Because this is a homework question, I'll leave as much as possible to you, so you learn.
Consider these two facts:
You must print the first character after you have printed the rest
If the string is empty, print nothing
Use these two facts are enough to build a recursive method.
Point 2. is the terminating condition. It's best to code this first.
Point 1. is the main method body, where printing the rest is done using recursion
Once you have your terminating condition and your recursive structure (often, a pre-order or a post-order operation), you can build a recursive method.
Note also the name of the method printBackwards() (not backwards()). That is, the method does the printing; it doesn't return the String backwards.
So, translating the above into pseudo-code (which in this case is practically the code):
if the string is empty do nothing
call self with the rest of the string
print the first character
First of all you need to print the output within the printBackwards function, so the main will look like this:
public static void main(String args[])
{
printBackwards("House");
}
Second, is the way recursion works. If you want it to be executed in the ascending order, you should do stuff before the self function call. Otherwise, in case of descending execution order, you code should be executed after the self calling function. These are the basic principles of the recursion function.
In this case, let's try to build the answer.
First, we need to handle the stop condition, which should be always written before the self calling function. The best and most common stop condition, is to reach to the end of something, in this case it is when we get an empty string, in all other cases we need to call the self function with a slight of a change, in this case it will be providing the rest of the string to the function:
if ( !length(s) )
{
//stop the recursion
return;
}
else
{
printBackwards(rest(s));
}
When you reach the stop recursion statement, from this point and on, it will close all the opened self function executions, therefor will go backward.
This is the perfect state of what we need to achieve, print the letters backward and because on each state of the printBackwards execution, we have sliced the string a bit from the left letters, it means that the first letter is the one we need.
For example, in case of the string House the last call of the printBackwards function will be when the s variable will hold the e value, because it is one stem from being cut-off to an empty string, when we reach the stop condition. In this case we want to print it out, but in the self call before this one, the s variable will hold the value se, because it is one step before cutting the first letter. So, we not want to print the whole value, but only the first letter of it, like this:
System.out.println(first(s));
Combining everything together, will result the following implementation:
public static String printBackwards(String s)
{
if ( !length(s) )
{
//stop the recursion
return;
}
else
{
printBackwards(rest(s));
System.out.println(first(s));
}
}
Hope, I explained it clearly.
Good luck!
How do global variables work in case of recursion functions?
I have a code below. Why does this prints 7 0's as output?
int giValue=6;
public static void main(String[] args) {
// TODO Auto-generated method stub
Demo obj1=new Demo();
obj1.fnReverse();
}
public void fnReverse(){
if(giValue>0){
giValue--;
fnReverse();
}
System.out.println(" "+giValue);
}
I would like to know where the global variable value is getting saved, and how the value is changing?
Thanks
It prints 7 zeroes because at the end of each recursive call you are printing the value of giValue. Since the method never reaches the print statement until giValue reaches 0, it prints only 0s when the recursion unwinds.
The value is changing due to the giValue--; line. giValue is not a global variable. It's an instance variable of your Demo class, and its value is initialized to 6 when you create the Demo instance.
There are 7 calls to the method - the initial call and 6 additional recursive calls. The first 6 calls decrement giValue, so during the 7th call its value is 0 and the recursion ends.
#Eran described the reason why you get 7 0s.
it is normally wrong to use global variables within recursive method. but if you really insists of doing it then one of way of printing 0 1 ... 6 would be
public void fnReverse(){
int printMeInstead=giValue;
if(giValue>0){
giValue--;
fnReverse();
}
System.out.println(" "+printMeInstead);
}
NOTE:
THIS WILL ONLY WORK FORM PRIMITIVE DATATYPE ( because the actual value gets copied not a reference to an object)
Assuming you do understand the logical flow of the program.
givalue=6; (givalue--)=>5; call fnReverse(); //print statement not yet reached
givalue=5; (givalue--)=>4; call fnReverse(); //print statement not yet reached
.
.
.
givalue=1; (givalue--)=>0; call fnReverse(); //print statement not yet reached
Now,
when givalue=0; //givalue>0 evaluates to false; first print statement reached
prints givalue as 0.
Similarly, for all 6 previous calls the print statement correctly prints the current value of givalue, which apparently is now 0 since it is a global variable.
So, the output is 7 zeros.
class Demo{
int giValue=6;
public static void main(String[] args) {
// TODO Auto-generated method stub
Demo obj1=new Demo();
obj1.fnReverse();
}
public void fnReverse(){
System.out.println(" "+giValue);
if(giValue>0){
giValue--;
fnReverse();
}
//System.out.println(" "+giValue);
}
}
This code would print from 6 to 0 in descending order.See it here.
Is there a way to return some value from within a for loop without jumping out of the loop?
I am implementing a static analysis tool where I have to analyze a list of methods (CFGs) in a for loop. The size of CFG list is not known in advance. Each method in the for loop has to return some value. As asked above, is there a way to do it in a loop without breaking the loop? One possible alternative comes in mind is that I can unroll the loop, assuming the maximum list size could be some fixed value. But this does not solve the problem completely. Any help would be appreciated.
code looks like below.
for(CFG cfg: cfgList)
{
val = analyze(cfg);
return val; //I want for loop not to stop here.
}
P.S. I cannot store the values in a list to return values later.
Edit1:
For example, consider following statements.
call method1();
st2;
st3;
...
This method1() can be any of five different methods. For all five possible options, I want to analyze each of them, return their values and analyze rest of the statements accordingly. So, I would analyze these 5 methods as below.
call method1-option1();
st2;
st3;
...
call method1-option2();
st2;
st3;
...
call method1-option3();
st2;
st3;
...
Hope, it helps in understanding the question.
No you can not return value from loop without jumping out of it. According to your need you have to save value in other list and you can return that list after finishing the loop.
In Java 8, you can do:
Iterator<AnalysisResult> lazyAnalysisResults = cfgList.stream()
.map(cfg -> analyze(cfg))
.iterator();
And then the Iterator will supply new analyzed results one at a time, without you needing to collect them all into a list first.
Prior to Java 8, if you want your transformation to be lazy, the best you can do is to implement an Iterator yourself:
public final class AnalyzingIterator extends Iterator<AnalysisResult> {
private final Iterator<CFG> iter;
public AnalyzingIterator(Iterator<CFG> iter) {
this.iter = iter;
}
#Override public boolean hasNext() {
return iter.hasNext();
}
#Override public AnalysisResult next() {
return analyze(iter.next());
}
#Override public boolean remove() {
throw new UnsupportedOperationException();
}
}
If you don't want to store results in a List and return it all together you can use callback mechanism.
Use analyze() to start a new thread passing cfg as well as reference to this. When processing is over make that processing thread call a callback method on your current instance / thread passing the analyzed value. Continue to do whatever you intend to do with this returned value in the callback method. And you don't have to alter your for loop.
I am using System.out.println in my code to track the execution of a program and get some useful output. This creates results like this in the console:
Main function. Program starts.
Method getArea. Getting values
Method getSide. Side is 6
Method getArea. First value is 6
Method getSide. Side is 8
Method getArea. Second value is 8
Method getArea. Area is 48
Main function. The final area is 48
I would like to create tha method, which adds a space in front of the output every time the code goes deeper in the method call stack. For example, the same code but instead of using System.out.println, now with Misc.smartPrintln:
Main function. Program starts.
Method getArea. Getting values
Method getSide. Side is 6
Method getArea. First value is 6
Method getSide. Side is 8
Method getArea. Second value is 8
Method getArea. Area is 48
Main function. The final area is 48
The method would have this definition:
public static void smartPrintln(String string);
I don't know how to implement this functionality. Any ideas how to solve this? And, could the use of a logger offer this functionality?
Create a temporary Throwable object.
Use its getStackTrace() method to analyze the stack and determine the level.
e.g.
public static void smartPrintln(String string) {
Throwable t = new Throwable();
StackTraceElement[] stackElements = t.getStackTrace();
int level = stackElements.length - 1; // don't forget our function adds a level
for (int i = 0; i < level; i++) {
System.out.print(' '); // could probably make this more efficient
}
System.out.println(string);
}
Interesting question. A more condense implementation of #ob1's suggestion:
public static void smartPrintln(String string) {
int i = new Throwable().getStackTrace().length - 1;
System.out.printf("%"+i+"s%s%n", "", string);
}
Another solution would be to "add the functionality" directly to System.out.println calls like this:
System.setOut(new PrintStream(System.out) {
public void println(String x) {
printf("%"+(new Throwable().getStackTrace().length - 1)+"s", "");
super.println(x);
}
});
After this point, all calls to System.out.println(String) will be processed by our "filtering" PrintStream implementation.
Use the Logger API or anyother third party API.