Recursion with termination condition Java - java

I'm teaching myself about recursive calling of methods in java. I'm constantly getting StackOverFlowErroron my implementation:
public class LimitedRecursion {
public void m(int limit) {
if (limit == 0) {
System.out.println("finished2");
}
m(limit - 1);
}
}
i have set the limit to 42 in the main. Can someone point me to the right direction on this? Its supposed to terminate once limit == 0

This doesn't finish the recursion, since you don't exit the method when the condition is met, and you still make the next recursive call (m(limit - 1);) :
if (limit == 0) {
System.out.println("finished2");
}
m(limit - 1);
This will end the recursion :
if (limit == 0) {
System.out.println("finished2");
return;
}
m(limit - 1);

The correct recursion can be :
public class LimitedRecursion {
public void m(int limit) {
if (limit == 0) {
System.out.println("finished2");
} else {
m(limit - 1);
}
}
}

Something like this, Add a return statement
public static void main(String[] args) {
System.out.println(m(5));
}
public static String m(int limit) {
if (limit == 0) {
return "finished";
}
return m(limit - 1);
}
output
finished

Related

function to find number of ways u can split n objects using parts up to m

I'm using recursion to solve the problem. On paper my answer should work so I went wrong with the code. However, I can't figure exactly where the problem is.
public class Partition {
public static void main(String[] args) {
System.out.println(part(6,4));
}
public static int part(int n, int m) {
if (n==0) {
return 1;
}
else if(m == 0 || n<0) {
return 0;
}
else {
return part(n-m, m) + part(n, m);
}
}
}
You need to reduce m only for the problem to return 9 as you indicated.
public static int part (int n, int m) {
if (n == 0) {
return 1;
} else if (m == 0 || n < 0) {
return 0;
} else {
return part(n - m, m--) + part(n, m);
}
}
I'm not sure what you're trying to do, but if it is to compute the combination it should look like this :
public static int part(int n, int m) {
if(m>n) { //This prevent a wrong input from the user
return part(m, n);
} else if (m==0 || m==n) { //This is your base case
return 1;
} else if(m < 0 || n<0) { //this should not happened, but you never know
return 0;
} else { //this is where you're making mistake(s)
//I don't know if I'm using the formula you are looking for
//But if not, make sure yours do not use part(n, m) otherwise it will run forever
return part(n-1, m) + part(n-1, m-1);
}
}

Recursive function counts down 4->0, but then counts up 0>4, how can I stop the count up

The aim of this code is to confirm the letter A appears 4 times exactly but using a recursive function. I can get it to count correctly, but as soon as it begins to leave the recursive stacks, it then +1 instead of -1 (I think because it is leaving the stack).
Is there a better way to handle this, has me very stuck.
public class App {
public static boolean isPresentNTimes(String sequence, char marker, int count) {
System.out.println("This is the count: " + count);
if (sequence.isEmpty() != true){
if(sequence.charAt(0) == marker) {
isPresentNTimes(sequence.substring(1), marker, count-1);
System.out.println("The count is" + count);
}
else {
isPresentNTimes(sequence.substring(1), marker, count);
}
}
if (count == 4){
return true;
} else {
return false;
}
}
public static void main(String []args){
String seq1 = "ABBAACBA";
System.out.println(isPresentNTimes(seq1, 'A', 4));
}
}
This is what you actually want to implement:
public static boolean isPresentNTimes(String sequence, char marker, int count) {
if(count < 0)
return false;
else if(count == 0 && sequence.isEmpty())
return true;
else if (!sequence.isEmpty()){
if(sequence.charAt(0) == marker) {
System.out.println("The count is " + count );
count--;
}
return isPresentNTimes(sequence.substring(1), marker, count);
}
else
return false;
}
Start with count=4 and decrement every time you found one element equals to mark. Make sure to add return before each recursive call (i.e., return isPresentNTimes (...)):
In your code you were comparing
if (count == 4){
return true;
} else {
return false;
}
if count == 4, which does not make sense since you start already with count = 4.
Hope this will give you the answer ->
static boolean ispresnt(String word, char c, int count) {
if (word.length() == 0) {
if (count == 0) {
return true;
}
return false;
}
return word.charAt(0) == c ?
ispresnt(word.substring(1), c, count - 1) : ispresnt(word.substring(1), c, count);
}

Recursive Java Method

I have this small block of code used to find the sum of certain numbers:
public class TestClass {
public static int sumOfNums(int num[], int int) {
if(int == num.length-1) return int;
else if( (num[int]%2==0) || num[int] <= 0 ) {
return num[int] + sumOfNums(num, int+1); }
else return 0 + sumOfNums(num, int+1);
}
public static void main(String[] args) {
int[] arr = {-2,0,8,4,5,6,10,-5,-2,7,9};
System.out.println(sumOfNums(arr, 0));
}
}
However, whenever I run the print statement I get the exception:
Exception in thread "main" java.lang.StackOverflowError
at TestClass.sumOfNums(TestClass.java:13)
at TestClass.sumOfNums(TestClass.java:10)
Can anybody help me?
As another user said, your recursion is never ending.
Changing arr[head-1] to head-1 should fix this problem on this line:
else return 0 + sumNegEven(arr, arr[head-1]);
and changing it here as well:
return arr[head] + sumNegEven(arr, arr[head-1]); }
public class TestClass {
public static int sumNegEven(int arr[], int head) {
if(head == 0) {
return 0;
} else if( arr[head]%2==0 || arr[head] <= 0 ) {
return arr[head] + sumNegEven(arr, head-1);
} else {
return 0 + sumNegEven(arr, head-1);
}
}
public static void main(String[] args) {
int[] arr = {-2,0,8,4,5,6,10,-5,-2,7,9};
System.out.println(sumNegEven(arr, arr.length-1));
}
}
By call calling the arr[head-1] you were calling value of the index not index and they last long because recursion is not terminated. If you calling head-1, you are calling actual index and will get answer 21 without exception.
this won't process the first item in the array
if(head == 0) {
return 0;
}
you will have to change it to
if(head < 0) {
return 0;
}

Creating a recursive sequence in Java?

I was wondering how could you write a recursive method that accepts an integer parameter (n) and writes the following sequence: n, n-1, n-2,n-3,..., 0, ... -(n-3), -(n-2), -(n-1), -n. For example: 5,4,3,2,1,0,-1,-2,-3,-4,-5
What would be the base case for this example?
How will the method know when to end?
So far I have:
public static void createSequence(int n) {
if (n== 0)
return;
else{
System.out.println(n);
createSequence(n-1);
}
}
This only creates a sequence of positive integers, how can I fix this code?
You just need to write -n after the recursive call:
public static void createSequence(int n) {
if (n == 0) {
System.out.println(n);
return;
}
else {
System.out.println(n);
createSequence(n-1);
System.out.println(-n);
}
}
Looks like I'm late to the party, but here's mine:
public static void createSequence(int n){
System.out.println(n);
if(n==0) return;
createSequence(n-Integer.signum(n));
System.out.println(-n);
}
Works with positive and negative input.
The easiest, I think, would be to write an auxiliary recursive method:
public static void createSequence(int n) {
writeSequence(n, -n);
}
private static void writeSequence(int current, int limit) {
if (current >= limit) {
System.out.println(current);
writeSequence(current - 1, limit);
}
}
In such cases, you usually use a helper method for the recursive call:
public static void createSequence(int n) {
createSequenceHelper(n, -n); // be sure that 'n' is positive here
}
private static void createSequenceHelper(int n, int limit) {
if (n >= limit) {
System.out.println(n);
createSequenceHelper(n - 1, limit);
}
}
You can pass original number as a second parameter to do a check :
public static void createSequence(int n, int limit) {
if (n < limit)
return;
else{
System.out.println(n);
createSequence(n-1, limit);
}
}
Also by using : createSequence(5, -5);, it will print:
5
4
3
2
1
0
-1
-2
-3
-4
-5
Fixed !
public static void createSequence(int n) {
if (n== 0){
System.out.println(0);
return;
}else{
System.out.println(n);
createSequence(n-1);
System.out.println(n*-1);
}
}
The best and easy way to solve your issue is the below code. Here start should be initialized to n before calling this recursive function. (start=n;)
public static void createSequence(int n, int start) {
if (start + n == 0)
return;
else{
System.out.println(n);
createSequence(n-1, start);
}
}

Recursive method checking whether a row of integers is descending: return true/false

I have to write a recursive method in Java that returns true if a row is descending and false it does not.
This is what I tried, but it doesn't work properly:
ArrayList<Integer> getallen = new ArrayList();
getallen.add(500);
getallen.add(400);
getallen.add(300);
getallen.add(200);
getallen.add(100);
getallen.add(0);
System.out.println(isDescending(getallen));
}
public static boolean isDescending(ArrayList<Integer> getallen) {
if (getallen.size() >= 2) {
if (getallen.get(0) < getallen.get(1)) {
return false;
} else if (getallen.size() > 0) {
getallen.remove(0);
return isDescending(getallen);
} else {
return true;
}
} else {
return false;
}
}
I think you have unnecessary cases if the size is less than 2 you can only assume true.
Try:
public static boolean isDescending(ArrayList<Integer> getallen) {
if (getallen.size() >= 2) {
if (getallen.get(0) < getallen.get(1)) {
return false;
} else {
getallen.remove(0);
return isDescending(getallen);
}
} else {
return true;
}
}
If I had to grade this, it would get a big fat X for
Having been fraudulently asked on stackoverflow
Being quite inefficient (try running this test on a list of a million elements, then realise that removing element 0 in an ArrayList causes all elements to shift down)
Instead consider:
public static boolean isDescending(List<Integer> getallen) {
return isDescending(getallen, 0);
}
public static boolean isDescending(List<Integer> getallen, int from) {
return from >= getallen.size() - 1
|| getallen.get(from) < getallen.get(from + 1)
&& isDescending(getallen, from + 1);
}
How about little bit more efficient approach with logarithmic recursion depth? Just as an exercise.
public static void main(String[] args) {
List<Integer> getallen = new ArrayList<Integer>();
getallen.add(500);
getallen.add(400);
getallen.add(300);
getallen.add(200);
getallen.add(100);
getallen.add(0);
System.out.println(isDescending(getallen));
}
public static boolean isDescending(List<Integer> getallen) {
return isDescending(getallen, 0, getallen.size());
}
private static boolean isDescending(List<Integer> getallen,
int start, int end) {
if (end - start <= 1)
return true;
if (end - start == 2) {
return getallen.get(start) > getallen.get(start + 1);
}
int middle = (start + end - 1) / 2 + 1;
return (getallen.get(middle - 1) > getallen.get(middle)) &&
isDescending(getallen, start, middle) &&
isDescending(getallen, middle, end);
}

Categories

Resources