Towers of Hanoi with Stack but without any recursion - java

I already got the Towers of Hanoi with recursion, it's also working without any problems. But now I'd like to know how it could work without recursion but with stack instead.
public class Hanoirecursive {
static void move (
int x,
char start,
char help,
char aim) {
if (x == 1)
System.out.println(" from " + start + " to " + aim);
else {
move(x-1,start, aim, help);
System.out.println(" from " + start + " to " + aim);
move(x-1,help, start, aim);
}
}
public static void main (String args[]) {
int x = Integer.parseInt(args[0]);
if (x > 0) {
System.out.println("Movements: ");
move(x,'A','B','C');
}
else
System.out.println("No negative number.");
}
}
I would like to.. convert this code so it works with a stack and no longer with recursion but I really don't know where to start. Could you give me some hints please?
For the stack I could find this on the internet:
public class Stack {
private int[] stackElements;
private int top;
public Stack(int a) {
stackElements = new int[a];
top = -1;
}
public boolean isEmpty() {
return top == -1;
}
public void push(int b) {
stackElements[++top] = b;
}
public int pop() {
if(isEmpty() ) {
System.out.println( "Empty stack" );
return -1;
}
else {
return stackElements[top--];
}
}
}
Any kind of help is very much appreciated! :)

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 do I keep getting stack overflow errors? Why does my function return at the first value? when start does != the last value

This is the question:
Write a recursive method that removes all consecutively occurring letters from a string of fixed size. E.g. “AAAbbCCCC” becomes “AbC”
My Code:
public static String NoRepeats(String n, int start) {
String x = "";
if(start == n.length()-1) {
return x;
}
if(n.charAt(start) == n.charAt(start+1)) {
return NoRepeats(n, start+1);
}
else {
x += n.charAt(start);
return NoRepeats(n,start+=1);
}
}
ok, so I wasn't sure why it would only return an empty string, So I fiddled around with the syntax.
FYI String n = "AAAABBBBCCCCDDDD"
In my recursive steps I couldn't use 'start ++ or start +1", it only worked when it was 'start +=1'. This will correct it.
This is my new code:
public static String NoRepeats(String n, int start) {
String x = "";
if(start == (n.length()-1)) {
x += n.charAt(start);
return x;
}
if(n.charAt(start) == n.charAt(start+1)) {
return NoRepeats(n, start+=1);
}
else {
x += n.charAt(start);
return x +NoRepeats(n,start+=1);
}
}
I was wondering why did the above returned empty string so I went and modify your codes to see how it's done.
String a = "";
String b = "";
try {
a = Tesst1.NoRepeats("AAAbbCCCC", 0, b);
} catch(Exception e) {
e.printStackTrace();
}
System.out.println(a);
}
public static String NoRepeats(String n, int start, String b) {
if(start == n.length()-1) {
return b += n.charAt(start - 1);
}
if(n.charAt(start) == n.charAt(start+1)) {
return NoRepeats(n, start+1, b);
}
else {
b += n.charAt(start);
return NoRepeats(n,start+1, b);
}
}
This should now yield AbC.
In your code x is local to function. So, with every call you lose the value of x. Also, there was little mistake in first statement.
In classic way, you could use the result of function:
public static String noRepeats(String n, int start) {
return (start == n.length() - 1) ? "" + n.charAt(start) :
(n.charAt(start) == n.charAt(start + 1)) ? noRepeats(n, start + 1) :
n.charAt(start) + noRepeats(n, start + 1);
public static void main(String[] args) {
System.out.println(noRepeats("AAAbbCCCC", 0));
}
Or need some buffer to accumulate new characters:
public static String noRepeats(String n) {
return noRepeats(n, new StringBuilder(), 0);
}
public static String noRepeats(String n, StringBuilder result, int start) {
if(start == n.length() - 1) {
return result.append(n.charAt(start)).toString();
}
if(n.charAt(start) == n.charAt(start + 1)) {
return noRepeats(n, result, start + 1);
}
else {
result.append(n.charAt(start));
return noRepeats(n, result, start + 1);
}
}
public static void main(String[] args) {
System.out.println(noRepeats("AAAbbCCCC"));
}

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

FIbonacci series using recursion error?

public class Fibonacci2 {
static int fib(int n) {
if(n==1 || n==2) {
return(1);
}
return fib((n-1)+fib(n-2));
}
// Stackoverflow error //
public static void main(String[] args) {
int i, n = 7;
for(i=1; i<=n; i++)
System.out.println("FIbonaci series" + fib(i));
}
}
This program suffer from runtime exception (stackoverflow) please tell how to deal with it.
You step through the code in your debugger and you will see that
return fib((n-1)+fib(n-2));
should be
return fib(n-1) + fib(n-2);
as what you have is like
return fib(fib(n-2));
which quickly creates very high levels of recursion.
replace fib((n-1)+fib(n-2)) with fib(n-1)+fib(n-2).
May be it will help you
public static void fib(int initial, int current, int n) {
int sum = 0;
sum = initial + current;
if (initial == 0) {
System.out.print(current + " ");
}
System.out.print(sum + " ");
initial = current;
current = sum;
if (n > 2) {
fib(initial, current, n - 1);
}
}

Recursive method to add odd numbers

I have the below snippet of code to use a recursive method to add the sum of odd numbers.
I have already coded the iterative method successfully that adds the sum of all odd numbers between n and m which are entered by the user. I'd like to reach that goal but am started slow to make sure I understand what is happening.
I know that it makes more sense to do it iteratively, however I am experimenting with the two types to see which is more efficient. I am stuck on the below as it is not doing what i want it to and i can't understand why.
import java.util.*;
public class SumofOdd
{
public static void main (String [] args)
{
int n = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter an odd number");
n = sc.nextInt();
int x = add(n);
}
public static int add(int x)
{
if (x == 0)
{
return 0;
}
else
{
return (x + add(x-1));
}
}
}
I have changed the above to the below. It compiles however stops after I enter the number.
import java.util.*;
public class SumofOdd
{
public static void main (String [] args)
{
int n = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter an odd number");
n = sc.nextInt();
if (n%2 == 0)
{
System.out.println("The number entered is even");
}
else
{
int x = add(n);
}
}
public static int add(int x)
{
if (x <= 0)
{
return 0;
}
else
{
return (x + add(x-2));
}
}
}
import java.util.*;
public class OddR{
public static void main (String Args [])
{
Scanner s = new Scanner(System.in);
System.out.println("Enter an odd number");
int max = s.nextInt();
if((max% 2) == 0) {
System.out.println(max + " is Even number and therefore is invalid");
}
else{
System.out.println("Enter a greater odd number");
int m = s.nextInt();
if (m <max){
System.out.println("Invalid data");
}
else{
if((m % 2) == 0) {
System.out.println(m + " is Even number and therefore is invalid");
}
else{
int data = (addodd(m)- addodd(max))+max;
System.out.print("sum:"+data);
}
}
}
}
public static int addodd(int m)
{
if(m<=0)
{
return 0;
}
if(m%2 != 0)
{
return (m+addodd(m-1));
}
else
{
return addodd(m-1);
}
}
}
This is the answer recursively of the sum of odd numbers from n to m
public int addOdds(int n) {
if (n <= 0) {
return 0;
}
if (n % 2 == 0) {
return addOdds(n - 1);
}
return x + addOdds(n - 1);
}
Take care, I never tested the code.
class Oddsum {
public int addodd(int n)
{
if(n<=0)
{
return 0;
}
if(n%2 != 0)
{
return (n+addodd(n-1));
}
else
{
return addodd(n-1);
}
}
}
public class Xyz {
public static void main (String[] v)
{
int n = 9;
Oddsum o = new Oddsum();
int data = o.addodd(n);
System.out.print("sum:"+data);
}
}
This is working fine
public static void main (String[] args){
public static int oddSum(int s){
if (s <= 0)
return 0;
else
return s + oddSum(s -2);
}
}

Categories

Resources