// Program to test solutions to problem #5 on the cse143 midterm, summer 2019. // Fill in your solution to isConsecutive, then compile and run the program. import java.util.*; public class Test5 { public static boolean isConsecutive(Stack s) { // fill in your solution here // you can also rename the parameter above } // this is the sample solution public static boolean isConsecutive2(Stack s) { if (s.size() <= 1) { return true; } else { Queue q = new LinkedList(); int prev = s.pop(); q.add(prev); boolean ok = true; while (!s.isEmpty()) { int next = s.pop(); if (prev - next != 1) { ok = false; } q.add(next); prev = next; } while (!q.isEmpty()) { s.push(q.remove()); } while (!s.isEmpty()) { q.add(s.pop()); } while (!q.isEmpty()) { s.push(q.remove()); } return ok; } } private static int testCount; private static int failCount; public static void main(String[] args) { test(new int[] {}); test(new int[] {13}); test(new int[] {5, 6}); test(new int[] {9, 8}); test(new int[] {12, 13, 14}); test(new int[] {12, 13, 8}); test(new int[] {8, 13, 14}); test(new int[] {3, 2, 1}); test(new int[] {2, 3, 12, 13}); test(new int[] {4, 5, 12, 14}); test(new int[] {15, 16, 17, 18, 19}); test(new int[] {15, 14, 17, 18, 19}); test(new int[] {0, 2, 3, 4, 5}); test(new int[] {20, 21, 22, 23, 24, 25}); test(new int[] {20, 21, 15, 23, 24, 25}); test(new int[] {20, 21, 22, 23, 14, 25}); test(new int[] {1, 2, 3, 4, 6, 7, 8, 10}); test(new int[] {4, 5, 8, 9, 12, 13, 15, 16}); if (failCount == 0) { System.out.println("passed all " + testCount + " tests"); } else { System.out.println("failed " + failCount + " of " + testCount + " tests"); } } public static void test(int[] data) { // s1 for testing sample, s2 for their code Stack s1 = new Stack(); Stack s2 = new Stack(); for (int i = 0; i < data.length; i++) { int n = data[i]; s1.push(n); s2.push(n); } System.out.println("stack = " + s1); boolean test1 = isConsecutive2(s1); System.out.println("isConsecutive = " + test1); boolean fail = false; try { boolean test2 = isConsecutive(s2); if (test1 != test2) { fail = true; System.out.println("yours = " + test2); } else if (!s1.equals(s2)) { fail = true; System.out.println("yours left stack = " + s2); } } catch (RuntimeException e) { int line = e.getStackTrace()[2].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(); } }