// Program to test solutions to problem #9 on the cse142 final, spring 2015. // Fill in your solution to findIndexes, then compile and run the program. import java.util.*; public class FinalTest9 { public static int[] findIndexes(int n, int[] data) { // fill in your solution here // you can also rename the parameters above } // this is the sample solution public static int[] findIndexes2(int n, int[] data) { int[] result = new int[n]; Arrays.fill(result, -1); for (int i = 0; i < data.length; i++) { if (data[i] >= 0 && data[i] < n && result[data[i]] == -1) { result[data[i]] = i; } } 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, 2, 1, 4, 0}); test(new int[] {4, 2, 1, 3, 23, 5, 15, 8, 42, 17}); test(new int[] {}); test(new int[] {5}); test(new int[] {3, 9}); test(new int[] {4, 2, 1, 3, 22, 5, 24, 3, 28, 2, 0, 4, 8, 42, 17, 0}); test(new int[] {7, -3, 4, 9, 8, -2, 0, 4, 2, 0, -3, 7, 5}); 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) { int[] copy = Arrays.copyOf(data, data.length); for (int i = 1; i <= 30; i += 3) { testCount++; int[] result2 = findIndexes2(i, data); int[] result1 = null; boolean fail = false; RuntimeException except = null; try { result1 = findIndexes(i, data); } catch (RuntimeException e) { fail = true; except = e; } fail = fail || !Arrays.equals(result1, result2) || !Arrays.equals(data, copy); if (fail) { System.out.println("testing findIndexes(" + i + ", " + 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)); data = Arrays.copyOf(copy, copy.length); } } 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); } } } } }