// Program to test solutions to problem #7 on the cse142 final, spring 2015. // Fill in your solution to expand, then compile and run the program. import java.util.*; public class FinalTest7 { public static int[] expand(int[] data) { // fill in your solution here // you can also rename the parameter above } // this is the sample solution public static int[] expand2(int[] data) { int len = 0; for (int i = 0; i < data.length / 2; i++) { len = len + data[2 * i]; } int[] result = new int[len]; int index = 0; for (int i = 0; i < data.length / 2; i++) { int times = data[2 * i]; int n = data[2 * i + 1]; for (int j = 0; j < times; j++) { result[index] = n; index++; } } return result; } private static int testCount, failCount; public static final int ERRORS_MAX = 15; public static void main(String[] args) { failCount = 0; test(new int[] {3, 8, 4, 2, 5, 1}); test(new int[] {2, 5, 6, 2, 0, 9, 8, 7}); test(new int[] {0, 14, 4, 2, 3, -8, 4, -2, 1, -1, 1, 1, 6, 8, 7, 7}); if (failCount == 0) { System.out.println("PASSED all " + testCount + " tests"); } else { System.out.println("failed " + failCount + " of " + testCount + " tests"); } } public static void test(int[] allData) { for (int i = 0; i <= allData.length / 2; i++) { testCount++; int[] data = Arrays.copyOf(allData, 2 * i); int[] copy = Arrays.copyOf(allData, 2 * i); int[] result2 = expand2(data); int[] result1 = null; boolean fail = false; RuntimeException except = null; try { result1 = expand(data); } catch (RuntimeException e) { fail = true; except = e; } fail = fail || !Arrays.equals(result1, result2) || !Arrays.equals(data, copy); if (fail) { System.out.println("testing expand(" + Arrays.toString(copy) + ")"); if (except != null) { StackTraceElement[] trace = except.getStackTrace(); int line = trace[0].getLineNumber(); System.out.println("Threw exception at line#" + line); } else { if (!Arrays.equals(result1, result2)) { System.out.println("correct: " + Arrays.toString(result2)); System.out.println("yours : " + Arrays.toString(result1)); } if (!Arrays.equals(data, copy)) { System.out.println("data was: " + Arrays.toString(copy)); System.out.println("data now: " + Arrays.toString(data)); } } System.out.println(); failCount++; if (failCount > ERRORS_MAX) { System.out.println("exceeds " + ERRORS_MAX + " errors"); System.out.println("with " + (testCount - failCount) + " correct"); System.exit(0); } } } } }