// Program to test solutions to problem #6 on the cse143 midterm, summer 2013. // Fill in your solution to isPairwiseConsecutive, then compile and run the program. import java.util.*; public class Test6 { public static boolean isPairwiseConsecutive(Stack s) { // fill in your solution here // you can also rename the parameter above } // this is the sample solution public static boolean isPairwiseConsecutive2(Stack s) { Queue q = new LinkedList(); while (!s.isEmpty()) q.add(s.pop()); while (!q.isEmpty()) s.push(q.remove()); boolean isConsecutive = true; while (!s.isEmpty()) { int n = s.pop(); q.add(n); if (!s.isEmpty()) { int m = s.pop(); q.add(m); if (Math.abs(n - m) != 1) { isConsecutive = false; } } } while (!q.isEmpty()) s.push(q.remove()); return isConsecutive; } private static int failCount; public static void main(String[] args) { int[][] data = {{}, {1}, {1, 2}, {2, 1}, {1, 3}, {3, 1}, {1, 2, 6, 7}, {1, 2, 6, 3}, {2, 1, 6}, {1, 2, 3, 4, 5}, {3, 2, -1, -2, 0, 1, 3}, {3, 2, -1, -2, 3, 0, 3}}; for (int[] set : data) { Stack s = new Stack(); for (int n : set) { s.push(n); } test(s); } if (failCount == 0) { System.out.println("all tests passed"); } else { System.out.println("failed " + failCount + " tests"); } } public static void test(Stack s) { System.out.println("stack = " + s); boolean test1 = isPairwiseConsecutive2(s); System.out.println("isPairwiseConsecutive2 = " + test1); boolean fail = false; try { Stack s2 = new Stack(); for (int n : s) s2.push(n); boolean test2 = isPairwiseConsecutive(s2); if (test1 != test2) { fail = true; System.out.println("yours = " + test2); } if (!s.equals(s2)) { fail = true; System.out.println("yours left stack = " + s2); } } catch (RuntimeException e) { int line = e.getStackTrace()[0].getLineNumber(); System.out.println(" threw " + e + " at line #" + line); fail = true; } if (fail) { System.out.println("failed"); failCount++; } else { System.out.println("passed"); } System.out.println(); } }