// Program to test solutions to problem #4 on the cse143x midterm, fall 2018. // Fill in your solution to mirrorCollapse, then compile and run the // program. Note that it does not test whether the exception is thrown. import java.util.*; public class FinalTest4 { public static void mirrorCollapse(Stack s) { // fill in your solution here // you can also rename the parameter above } // this is the sample solution public static void mirrorCollapse2(Stack s) { Queue q = new LinkedList(); while (!s.isEmpty()) { q.add(s.pop()); } int oldSize = q.size(); for (int i = 0; i < oldSize / 2; i++) { s.push(q.remove()); } if (oldSize % 2 == 1) { q.add(q.remove()); } while (!s.isEmpty()) { q.add(q.remove() + s.pop()); } while (!q.isEmpty()) { s.push(q.remove()); } } private static int testCount; private static int failCount; public static void main(String[] args) { test(new int[] {}); test(new int[] {1, 20}); test(new int[] {1, 2, 30}); test(new int[] {1, 2, 30, 40}); test(new int[] {1, 2, 3, 40, 50}); test(new int[] {1, 2, 3, 40, 50, 60}); test(new int[] {1, 2, 3, 4, 50, 60, 70}); test(new int[] {1, 2, 3, 4, 50, 60, 70, 80}); test(new int[] {7, 1, 4, 18, 23, 0, -5, 12}); if (failCount == 0) { System.out.println("passed all tests"); } else { System.out.println("failed " + failCount + " of " + testCount + " tests"); } } public static void test(int[] data) { Stack s = new Stack(); for (int n : data) { s.push(n); } test(s); } public static void test(Stack s) { Stack s2 = new Stack(); for (int n : s) { s2.push(n); } System.out.println("original = " + s); mirrorCollapse2(s); System.out.println("result = " + s); boolean fail = false; try { mirrorCollapse(s2); } catch (RuntimeException e) { int line = e.getStackTrace()[2].getLineNumber(); System.out.println(" threw " + e + " at line #" + line); fail = true; } if (!fail && !s.equals(s2)) { System.out.println("yours = " + s2); fail = true; } testCount++; if (fail) { System.out.println("failed"); failCount++; } else { System.out.println("passed"); } System.out.println(); } }