// Program to test solutions to problem #10 on the cse142 final, autumn 2014. // Fill in your solution to removeZeros, then compile and run the program. import java.util.*; public class FinalTest10 { public static void removeZeros(int[] list) { // fill in your solution here // you can also rename the parameter above } // this is the sample solution public static void removeZeros2(int[] list) { int numNonZero = 0; for (int i = 0; i < list.length; i++) { if (list[i] != 0) { list[numNonZero] = list[i]; numNonZero++; } } for (int i = numNonZero; i < list.length; i++) { list[i] = 0; } } private static int count, failCount; private static Random r; public static final int ERRORS_MAX = 10; public static void main(String[] args) { failCount = 0; r = new Random(); for (int i = 0; i <= 15; i++) { test(i); } if (failCount == 0) { System.out.println("PASSED all " + count + " tests"); } } public static void test(int i) { int[] data = new int[i]; test(data, 0); } public static void test(int[] data, int index) { if (index == data.length) { count++; int[] data1 = Arrays.copyOf(data, data.length); int[] data2 = Arrays.copyOf(data, data.length); boolean fail = false; RuntimeException except = null; try { removeZeros(data1); } catch (RuntimeException e) { fail = true; except = e; } removeZeros2(data2); fail = fail || !Arrays.equals(data1, data2); if (fail) { if (except != null) { StackTraceElement[] trace = except.getStackTrace(); int line = trace[0].getLineNumber(); System.out.println("FAIL with exception for " + Arrays.toString(data) + " at line#" + line); } else { System.out.println("FAIL for " + Arrays.toString(data)); } System.out.println("Correct: " + Arrays.toString(data2)); System.out.println("Theirs: " + Arrays.toString(data1)); System.out.println(); failCount++; if (failCount > ERRORS_MAX) { System.out.println("exceeds " + ERRORS_MAX + " errors"); System.out.println("with " + count + " correct"); System.exit(0); } } } else { data[index] = 0; test(data, index + 1); do { data[index] = r.nextInt(51) - 25; } while (data[index] == 0); test(data, index + 1); } } }