// Program to test solutions to problem #5 on the cse14 midterm, autumn 2014. // Fill in your solution to parityMatches, then compile and run the program. // note: this program doesn't test the exception that should be thrown import java.util.*; public class Test5 { public static int parityMatches(Stack s1, Stack s2) { // fill in your solution here // you can also rename the parameters above } // this is the sample solution public static int parityMatches2(Stack s1, Stack s2) { if (s1.size() != s2.size()) { throw new IllegalArgumentException(); } Queue q = new LinkedList(); int count = 0; while (!s1.isEmpty()) { int num1 = s1.pop(); int num2 = s2.pop(); if (num1 % 2 == num2 % 2) count++; q.add(num1); q.add(num2); } while (!q.isEmpty()) s1.push(q.remove()); while (!s1.isEmpty()) q.add(s1.pop()); while (!q.isEmpty()) { s2.push(q.remove()); s1.push(q.remove()); } return count; } private static int testCount; private static int failCount; public static void main(String[] args) { for (int i = 0; i <= 6; i++) { test(i); } } public static void test(int length) { Stack s1 = new Stack(); Stack s2 = new Stack(); explore(s1, s2, length); if (failCount == 0) { System.out.println("passed all " + testCount +" tests "); } else { System.out.println("failed " + failCount + " of " + testCount + " tests"); } } public static void explore(Stack s1, Stack s2, int length) { if (length == 0) { System.out.println("stack 1 = " + s1); System.out.println("stack 2 = " + s2); int count1 = parityMatches2(s1, s2); System.out.println("parityMatches = " + count1); boolean fail = false; try { Stack s3 = new Stack(); Stack s4 = new Stack(); for (int n : s1) s3.push(n); for (int n : s2) s4.push(n); int count2 = parityMatches(s3, s4); if (count1 != count2) { fail = true; System.out.println("yours = " + count2); } if (!s1.equals(s3) || !s2.equals(s4)) { fail = true; System.out.println("yours left stack1 = " + s3); System.out.println("yours left stack2 = " + s4); } } catch (RuntimeException e) { int line = e.getStackTrace()[0].getLineNumber(); System.out.println(" threw " + e + " at line #" + line); fail = true; } testCount++; if (fail) { System.out.println("failed"); failCount++; } else { System.out.println("passed"); } System.out.println(); if (failCount > 20) { System.out.println("quitting after 20 failures..."); System.exit(1); } } else { // even/even case s1.push(42); s2.push(64); explore(s1, s2, length - 1); // even/odd case s2.pop(); s2.push(35); explore(s1, s2, length - 1); // odd/odd case s1.pop(); s1.push(17); explore(s1, s2, length - 1); // odd/even case s2.pop(); s2.push(94); explore(s1, s2, length - 1); s1.pop(); s2.pop(); } } }