// Program to test solutions to problem #5 on the cse143 midterm, fall 2012. // Fill in your solution to compressDuplicates, then compile and run the program. import java.util.*; public class Test5 { public static void compressDuplicates(Stack s) { // fill in your solution here // you can also rename the parameter above } // this is the sample solution public static void compressDuplicates2(Stack s) { Queue q = new LinkedList(); while (!s.isEmpty()) q.add(s.pop()); while (!q.isEmpty()) s.push(q.remove()); while (!s.isEmpty()) q.add(s.pop()); if (!q.isEmpty()) { int last = q.remove(); int count = 1; while (!q.isEmpty()) { int next = q.remove(); if (next == last) count++; else { s.push(count); s.push(last); count = 1; last = next; } } s.push(count); s.push(last); } } public static void main(String[] args) { test(new int[] {2, 2, 2, 2, 2, -5, -5, 3, 3, 3, 3, 4, 4, 1, 0, 17, 17}); test(new int[] {8}); test(new int[] {}); test(new int[] {1, 1}); test(new int[] {1, 1, 1}); test(new int[] {1, 1, 1, 1}); test(new int[] {10, 20, 30, 40}); test(new int[] {10, 20, 10, 20, 10, 20}); } public static void test(int[] data) { Stack s1 = new Stack(); Stack s2 = new Stack(); for (int n : data) { s1.push(n); s2.push(n); } System.out.println("stack = " + s1); compressDuplicates2(s1); System.out.println("result = " + s1); boolean fail = false; try { compressDuplicates(s2); if (!s1.equals(s2)) { fail = true; System.out.println("yours = " + s2); } } catch (RuntimeException e) { System.out.println("yours threw " + e); fail = true; } if (fail) System.out.println("failed"); else System.out.println("passed"); System.out.println(); } }