Skip to content

Instantly share code, notes, and snippets.

@guyhughes
Last active February 18, 2016 21:12
Show Gist options
  • Save guyhughes/f70c434d7b3e8683bf5d to your computer and use it in GitHub Desktop.
Save guyhughes/f70c434d7b3e8683bf5d to your computer and use it in GitHub Desktop.
ITI1121 exam question from 2013/2014, implemented
class AStack implements Stack {
public static final int MAX_ITEMS = 1000;
public static final int ITERATIONS = 9;
private int items[] = new int[MAX_ITEMS];
private int i = 0;
public void push(int item) {
if (i < MAX_ITEMS) {
items[i++] = item;
}
}
public int pop() {
if (i <= 0)
return Integer.MIN_VALUE; // this could be any garbage number, or we can cause an error and crash the program
return items[--i];
}
public boolean isEmpty() {
return (i == 0);
}
public static boolean isSkipped(Stack s1, Stack s2) {
boolean return_value = false;
boolean complete = false;
int z1_element, z2_element;
Stack z1, z2;
if (s1.isEmpty() && s2.isEmpty())
return true;
z1 = new AStack();
z2 = new AStack();
// reverse s1 and s2 into z1 and z2 respectively
while (!s1.isEmpty()) {
z1.push(s1.pop());
}
while (!s2.isEmpty()) {
z2.push(s2.pop());
}
// the first element should be the same in both z1 and z2
z1_element = z1.pop();
z2_element = z2.pop();
s1.push(z1_element);
s2.push(z2_element);
if (z1_element != z2_element) {
// here the first element in z1 and z2 is not the same
// therefore, isSkipped → false
complete = true;
}
while (!complete) {
if (z1.isEmpty()) {
if (z2.isEmpty()) {
return_value = true;
} // else: return_value = false;
complete = true;
break;
}
// every second element in z1 (after the first) should be the same as the next element in z2
s1.push(z1.pop());
if (z2.isEmpty()) {
if (z1.isEmpty()) {
return_value = true;
} // else: return_value = false;
complete = true;
break;
}
z1_element = z1.pop();
z2_element = z2.pop();
s1.push(z1_element);
s2.push(z2_element);
if (z1_element != z2_element) {
complete = true;
break;
}
}
while (!z1.isEmpty()) {
s1.push(z1.pop());
}
while (!z2.isEmpty()) {
s2.push(z2.pop());
}
return return_value;
}
public static void main(String[] args) {
Stack s1, s2;
s1 = new AStack();
s2 = new AStack();
fillStacks(s1,s2);
for (int i = 1; i < ITERATIONS; ++i) {
System.out.printf("%d\t s1: %d \t s2: %d\n", i, s1.pop(), s2.pop());
}
fillStacks(s1,s2);
System.out.println("\nisSkipped: " + AStack.isSkipped(s1, s2) + "\n");
for (int i = 1; i < ITERATIONS; ++i) {
System.out.printf("%d\t s1: %d \t s2: %d\n", i, s1.pop(), s2.pop());
}
}
public static void fillStacks(Stack s1, Stack s2){
for (int i = 1; i < ITERATIONS; ++i) {
int data = i + 10000;
s1.push(data);
if (i % 2 != 0)
s2.push(data);
}
}
}
package guy;
public interface Stack {
void push(int item);
int pop();
boolean isEmpty();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment