Please provide guidance in understanding recursion [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
public static int countX(String str) {
if (str.length() == 0) {
return 0;
}
if (str.charAt(0) == 'x') {
return 1 + countX(str.substring(1));
} else {
return countX(str.substring(1));
}
}
Given an input String of "xxx", the method above shall return 3.
I understand the flow of the method, the line "return 1 + countX(str.substring(1));" adds one if an 'x' is found. What I don't understand is how does that return value carry over to the next iteration/recursion? I don't see the value of the increment stored anywhere.

Look at the line return 1 + countX(str.substring(1));
Now suppose that str was "xx", so the substring passed to the recursive call is "x".
So in that call, since the first character is 'x', it again executes
return 1 + countX(str.substring(1));
in the next recursive call, the substring is empty, so it returns zero to the previous call, which then returns (1+0) to its previous call, which returns ( 1 + (1 +0) ) to the initial call of the method, so the result for the String "xx" becomes 1+1+0 = 2.

Related

Using ASCII to find valid Anagram [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
Why doesn't this solution work for finding valid anagram?
26/36 test cases get passed in LeetCode.
class Solution {
public boolean isAnagram(String s, String t) {
int sASCII = 0, tASCII = 0;
if(s.length() != t.length()) {return false;}
else{
for(int i = 0 ; i < s.length(); i++){
sASCII += (int)s.charAt(i);
tASCII += (int)t.charAt(i);
}
}
if(sASCII == tASCII){
return true;
}
return false;
}
}
The sums tASCII and sASCII can be equal even if the numbers are not anagrams. Let's say that you can get the number 100 by adding 60+40, but you can also get it by adding 70+30, so i recommend to use a HashMap to note every occurence of every letter or to sort the strings as arrays of chars and then compare them.

Java indexOf("") returns 0 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Can someone help and explain whether indexOf("") returns 0 is predefined same as -1 by returning a negative result?
Thanks and Happy Easter to all!
ps. the following link was helpful, but it does not contain the exact answer to my question
"Hello".indexOf("") returns 0
public class ExIndexOf {
public static void main(String[] args) {
String s = "We learn Java.";
System.out.println(s.indexOf("ava")); // -> 10
System.out.println(s.indexOf("java")); // -1
System.out.println(s.indexOf(" ")); // -> 2
System.out.println(s.indexOf("")); // -> 0
}
}
Because indexOf returns the first position (index) of its argument in the string. Strings in Java, like arrays and collections are zero-indexed, meaning that the index 0 describes the first item. Index 1 is the second item and index n describes the n+1th item. Many functions return the (invalid) index -1 (a "magic" value) to denote "not found" or "error".
The empty string is contained in every string multiple times. The first position where it can be found is at position 0. Think of it as: String s = "" + "We learn Java." (or even more verbose: s = "" + "W" + "" + "e" + "" + " " + "" + "l" + …).
String s = "We learn Java.";
System.out.println(s.indexOf("")); // -> 0
System.out.println(s.indexOf("W")); // 0
System.out.println(s.indexOf("e")); // -> 1
System.out.println(s.indexOf(" ")); // -> 2
System.out.println(s.indexOf("not found")); // -> -1

Why does the output change in a recursive method? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have created a simple recursive method like this:
public void rec(int a) {
if(a > 0) {
rec(a - 1);
System.out.println(a);
}
}
the output for this method is:
1
2
3
4
5
And that's just great but the question is why when I write the print command outside the if statement the output starts from 0 not 1?
public void rec(int a) {
if(a > 0) {
rec(a - 1);
}
System.out.println(a);
}
why when I write the print command outside the if statement the output starts from 0 not 1?
Because, in the first version, the if (a > 0) prevents the function from printing 0. How about we look at what is happening here by including both prints:
public void rec ( int a) {
if(a>0) {
rec(a-1);
System.out.println("Inside if: " + a);
}
System.out.println("After if: " + a);
}
In the code
public void rec(int a) {
if(a > 0) {
rec(a - 1);
System.out.println(a);
}
}
you recursively invoke the method rec() with "a" as the parameter value for the first method invocation and then "a-1" for all the subsequent method invocations.
The rec() method has if clause which only executes if the value of parameter "a" received is greater than 0.
if the value of "a" is 0 then the method simply does nothing and returns back to invoking point and prints the value of variable a in that method scope.
An important point is that the value of "a" in a method scope is not being altered only the parameter to the next method call is being altered (i.e a-1)
Let' say the initial method call is something like
rec(5) // <-- method invoked with a = 5
//method definition
public void rec(int a) { // <-- a = 5
if(a > 0) { // 5 > 0 ? True
rec(a - 1); // rec(5-1) ie rec(4) but a = 5 still
System.out.println(a); // <-- a = 5 in this method scope
}
}
To have a better idea you can read on scopes,methods and call Stacks.
This will give a better grasp on recursion as well.

Why this recursive method is considered a factorial? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I understand everything this method does up until m=1 and n=1. What happens after if() when m=1 and n=1 is problematic.
public class exc {
public static void main(String[] args) {
System.out.println(prod(1, 4));
}
public static int prod(int m, int n) {
if (m == n) {
return n;
} else {
int recurse = prod(m, n - 1);
int result = n * recurse; // how n gets its value here?
return result;
}
}
}
What is the value of recurse? I mean how prod yields only one
integer? (since it has two integers)
In if, when m=1 and n=1 return value is 1 so why the program doesn't terminate at there? And instead it terminates after "return result;" in else?
After m=1 and n=1, n is 2 (in recurse) ; how is n set to 2? Is it because 2 is still in memory and had to be dealt with?
I checked this page
I also used println after different lines to see the out put, but that didn't help either. I also used a debugger.
Your program return the factorial when m = 1.
Take this example: (m=1, n=4)
4 != 1 -> so you call recursively prod(1, 3)
3 != 1 -> so you call recursively prod(1, 2)
2 != 1 -> so you call recursively prod(1, 1)
1 == 1 -> you return 1 to the last call
In this call, recurse = 1 and n = 2 so you return 2 to the upper call
Here, recurse = 2, n = 3, so you return 6 to the upper call
Here, recurse = 6, n = 4, so you return 24 to the upper call
END OF FUNCTION, result is 24 which is 4!
Every time you are calling the function prod recursively, the current function prodA is paused (saving the values of its variables in memory) to execute the new function prodB until prodB returns something to prodA. Then A continues to execute itself (loading back its values from memory)

Repeat String Recursively [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This is homework. I get the logic but i got stuck on the code. I've done it with normally way and it takes 1 week to get the code. I need to get repeat string with recursive way in Java.
This is my code :
static String repeatString (final int n, final String[] syllables, final String currentWord) {
if (n == 0) {
System.out.println(currentWord);
} else {
for (int i = 0; i < syllables.length; i++) {
repeatString(n - 1, syllables, currentWord + syllables[i]);
}
}
return "";
}
if i call in main method like
String[] str = {"a", "b"};
repeatString(1, str, " ");
then i get output (a,b) if i change to
repeatString(2,str," ");
then i get output ( aa,ab,ba,bb) if i change to
repeatString(3,str," ");
then i get output (aaa,aab,aba,abb,baa,bab,bba,bbb) and so on.
So basically it is like 2 to the power to n. If n=1, i got 2, if n=3, i got 8, and so on.
I would be grateful if someone can help me to get this code in recursive way.
Any help is much appreciated.
The method you have there is recursive already. Being recursive does NOT mean it should have no for loops. A recursive method in cheap words means the method calls itself, which yours does.

Categories

Resources