// Program to test solutions to problem #5 on the cse143 midterm, spring 2018. // Fill in your solution to extractOddIndexes, then compile and run the program // note: this program doesn't test the exception that should be thrown import java.util.*; class ArrayIntList { public ArrayIntList extractOddIndexes() { // fill in your solution here } public ArrayIntList extractOddIndexes2() { ArrayIntList result = new ArrayIntList(); for (int i = 0; i < size / 2; i++) { result.elementData[i] = elementData[2 * i + 1]; elementData[i] = elementData[2 * i]; } result.size = size / 2; if (size % 2 == 0) { size = size / 2; } else { elementData[size / 2] = elementData[size - 1]; size = size / 2 + 1; } return result; } private int[] elementData; // list of integers private int size; // current number of elements in the list public static final int DEFAULT_CAPACITY = 100; // post: constructs an empty list of default capacity public ArrayIntList() { elementData = new int[DEFAULT_CAPACITY]; size = 0; } // post: creates a comma-separated, bracketed version of the list public String toString() { if (size == 0) { return "[]"; } else { String result = "[" + elementData[0]; for (int i = 1; i < size; i++) { result += ", " + elementData[i]; } result += "]"; return result; } } // post: appends the given value to the end of the list public void add(int value) { elementData[size] = value; size++; } } public class Test5 { private static int testCount, failCount; public static void main(String[] args) { test(new int[] {13, 5, 7, 12, 42, 8, 23, 31}); test(new int[] {14, -64, 16, 88, 21, 17, -93, 81, 17}); for (int i = 0; i < 10; i++) { int[] data = new int[i]; for (int j = 0; j < i; j++) { data[j] = j; } test(data); } if (failCount == 0) { System.out.println("passed all tests"); } else { System.out.println("failed " + failCount + " of " + testCount + " tests"); } } public static void test(int[] data) { ArrayIntList list1 = new ArrayIntList(); ArrayIntList list2 = new ArrayIntList(); for (int n : data) { list1.add(n); list2.add(n); } System.out.println("original list = " + list1); ArrayIntList list3 = list1.extractOddIndexes2(); boolean fail = false; ArrayIntList list4 = null; try { list4 = list2.extractOddIndexes(); } catch (RuntimeException e) { int line = e.getStackTrace()[0].getLineNumber(); System.out.println(" threw " + e + " at line #" + line); fail = true; } if (!fail) { if (!list3.toString().equals(list4.toString())) { System.out.println("expected extracted list = " + list3); System.out.println("your extracted list = " + list4); fail = true; } else { System.out.println("extracted lists match"); } if (!list1.toString().equals(list2.toString())) { System.out.println("expected list after = " + list1); System.out.println("your list after = " + list2); fail = true; } else { System.out.println("lists after match"); } } testCount++; if (fail) { System.out.println("failed"); failCount++; } else { System.out.println("passed"); } System.out.println(); } }