Creating a recursive sequence in Java? - 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);
}
}

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);
}
}

Why is there a logical error if (arr.length == 0) {return Integer.MAX_VALUE;} is placed where it is?

I ran my code with if(arr.length == 0){
return Integer.MAX_VALUE;} at the beginning of the method. However, is there a logic error regarding where if(arr.length == 0){
return Integer.MAX_VALUE; is placed?
import java.util.*;
class RecursiveMethods{
public static int smallest(int[] arr){ // if size of array is 0, return max value
// The next 4 lines are the changes I have made.
if Math.min(arr[0],smallest(Arrays.copyOfRange(arr,1,arr.length)));
} // Return minimum of first element and ans obtained by subarray
else { if(arr.length == 0){
return Integer.MAX_VALUE;
}
public static int smallest(int[][] arr){
if(arr.length==0){
return Integer.MAX_VALUE;
}
return Math.min(smallest(arr[0]),smallest(Arrays.copyOfRange(arr,1,arr.length)));
}
public static String repeat(String s, int n){ // n=0, return empty string
if(n==0)return "";
return s+repeat(s,n-1);
}
public static void main(String[] args) {
System.out.println(smallest(new int[]{2,4,3,89,0,-9}));
System.out.println(smallest(new int[][]{{1,2,3,4,1,0},{0,-8,-90}}));
System.out.println(repeat("Hello",3));
}
}
No, this is not a logical error. You're correct because you use Math.min() and for corner case, you can use smth that you can treat as a marker. So, Math.min(arr[i], Integer.MAX_VALUE) will retrieve arr[i].
Additionally, I recommend you to pay attention to the performance of your methods. It's better not to make a copy of array on each recursion and not use String concatenation:
class RecursiveMethods {
public static int smallest(int[] arr) {
return smallest(arr, 0);
}
private static int smallest(int[] arr, int i) {
if (i >= arr.length)
return Integer.MAX_VALUE;
return Math.min(arr[i], smallest(arr, i + 1));
}
public static String repeat(String s, int n) {
return repeat(s, n, new StringBuilder(s.length() * n)).toString();
}
private static StringBuilder repeat(String s, int n, StringBuilder buf) {
if (n <= 0)
return buf;
buf.append(s);
return repeat(s, n - 1, buf);
}
}

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;
}

Substring between 2 indexes using recursion

I started learning Java, currently I'm playing around with recursion.
I wanted to try and make a substring method which will substring from both sides by 1 character until we get the desired string.
I managed to do the first part but I'm having problem figuring out how to substring from the back.
n and m should be the indexes between which we want to substring (inclusive).
In this example result of method should be "bstri"
Here is my code:
public static void main(String[] args) {
String s = "substringme";
System.out.println(rec(s,2,6));
}
public static String rec(String s, int n, int m) {
if(n == 0 /* && missing 2nd part of condition */){
return s;
} else {
if(n>0){
s = s.substring(1);
n--;
}
if(/* missing condition */){
s= s.substring(0, s.length()-1);
}
return rec(s,n,m);
}
}
I would appreciate any help I can get.
So fixing your recursive method is fairly easy. We just do exactly the same as you did for n:
public static String rec(String s, int n, int m) {
if (n == 0 && m == 0) {
return s;
}
else {
if(n > 0) {
s = s.substring(1);
n--;
}
if(m > 0) {
s = s.substring(0, s.length()-1);
m--;
}
return rec(s,n,m);
}
}
The issue now is that the value of m given as input is measured from the start of the String and it would be way more convenient for us if it were measured from the end of the String.
We can introduce a new method to do this for us which acts as our entry point to the recursive method:
public static String substr(String s, int n, int m) {
final int newM = s.length() - m - 1; //-1 to be inclusive of the char
return rec(s, n, newM);
}
You would then change your main method to call substr() instead:
public static void main(String[] args) {
String s = "substringme";
System.out.println(substr(s,2,6));
}
I often find myself writing these kind of "entry point" methods when I'm using recursive methods. If you were doing this properly, substr would be your public-facing method and rec would be private.
I propose that you do m-- in the first loop because the definition of m as an index changes when you shorten s from the front.
public static String rec(String s, int n, int m) {
if(n == 0 && m == s.length() - 1){
return s;
} else {
if (n > 0) {
s = s.substring(1);
n--;
m--;
}
if (m < s.length() - 1) {
s = s.substring(0, s.length() - 1);
}
return rec(s, n, m);
}
}
What you could do is look for the difference between m and the length of the string, and cut off characters from the end of the string until it is the correct length.
import java.util.*;
public class Test {
public static void main(String[] args) {
String s = "substringme";
System.out.println(rec(s,2,6));
}
public static String rec(String s, int n, int m) {
if(n == 0 && s.length()-m < 1){
return s;
} else {
if(s.length()-m > 1){
s= s.substring(0, s.length()-1);
}
else if(n>0){
s = s.substring(1);
n--;
}
return rec(s,n,m);
}
}
}
Also shouldn't substring from 2 to 6 be "bstr", not "bstri"?
System.out.println(s.substring(2, 6)); //equals bstr

Recursion with termination condition 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

Categories

Resources