Question
I am trying to create an Iterative solution. Can you help pinpoint where my coding is off? Thanks. public class TowersOfHanoiIteration { class Stack {
I am trying to create an Iterative solution. Can you help pinpoint where my coding is off? Thanks.
public class TowersOfHanoiIteration {
class Stack {
int maxSize;
int topOfArray;
int array[];
}
Stack newStack(int maxSize) {
Stack stack = new Stack();
stack.maxSize = maxSize;
stack.topOfArray = -1;
stack.array = new int[maxSize];
return stack;
}
boolean stackIsFull (Stack stack) {
return (stack.topOfArray == stack.maxSize -1);
}
boolean stackIsEmpty (Stack stack) {
return (stack.topOfArray == -1);
}
void push (char start, int data) {
if (stackIsFull(start))
return;
start.array[++start.topOfArray] = data;
}
int pop (Stack stack) {
if (stackIsEmpty(stack))
return Integer.MIN_VALUE;
return stack.array[stack.topOfArray--];
}
void moveBetweenTowers (Stack Tower1, Stack Tower2, char start, char next) {
int Tower1Top = pop(Tower1);
int Tower2Top = pop(Tower2);
if (Tower1Top == Integer.MIN_VALUE) {
push(Tower1, Tower2Top);
moveDisk (next, start, Tower2Top);
} else if (Tower2Top == Integer.MIN_VALUE) {
push(next, Tower1Top);
moveDisk(start, next, Tower1Top);
} else if (Tower1Top > Tower2Top) {
push(start, Tower1Top);
push(start, Tower2Top);
moveDisk(start, next, Tower1Top);
} else {
push(next, Tower2Top);
push(next, Tower1Top);
moveDisk(start, next, Tower1Top);
}
}
void moveDisk (char startTower, char nextTower, int Disk) {
System.out.println("Move disk " + Disk + " from " + startTower + " to " + nextTower);
}
void TowersOfHanoiIterative (int totalDisks, Stack Tower1, Stack stackEmpty, Stack Tower2) {
int i;
int maxMoves;
char start ='A', next = 'B', a ='C';
if (totalDisks % 2 == 0) {
char temp = next;
next = start;
start = temp;
}
maxMoves = (int)(Math.pow(2, totalDisks) - 1);
for (i = totalDisks; i >= 1; i--)
push(start, i);
for (i =1; i <=maxMoves; i++) {
if (i%3 == 1)
moveBetweenTowers(Tower1,Tower2, start, next);
else if (i % 3 == 2)
moveBetweenTowers(Tower1, stackEmpty, start, a);
else if (i%3 == 0 )
moveBetweenTowers(stackEmpty, Tower2, a, next);
}
}
public static void main (String args[]) {
int totalDisks = 3;
TowersOfHanoiIteration ob = new TowersOfHanoiIteration();
Stack Tower1, Tower2, stackempty;
Tower1 = ob.createStack(totalDisks);
Tower2 = ob.createStack(totalDisks);
stackEmpty = ob.createStack(totalDisks);
ob.TowersOfHanoiIterative(totalDisks, Tower1, stackEmpty, Tower2);
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started