// Program to test solutions to problem #5 on the cse143 midterm, winter 2018. // Fill in your solution to fromCounts, 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 fromCounts() { // fill in your solution here } public ArrayIntList fromCounts2() { ArrayIntList result = new ArrayIntList(); int size2 = 0; for (int i = 0; i < size; i += 2) { for (int j = 0; j < elementData[i]; j++) { result.elementData[size2] = elementData[i + 1]; size2++; } } result.size = size2; 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[] {}); test(new int[] {3, 8}); test(new int[] {4, 2, 5, 4}); test(new int[] {0, 7, 2, 1, 1, 2}); test(new int[] {5, 42, 13, 2, 0, 5, 3, 7}); test(new int[] {5, 2, 2, -5, 4, 3, 2, 4, 1, 1, 1, 0, 2, 17}); 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("list of pairs = " + list1); ArrayIntList list3 = list1.fromCounts2(); System.out.println("expanded list = " + list3); boolean fail = false; ArrayIntList list4 = null; try { list4 = list2.fromCounts(); System.out.println("yours = " + list4); if (!list3.toString().equals(list4.toString())) { fail = true; } } catch (RuntimeException e) { int line = e.getStackTrace()[0].getLineNumber(); System.out.println(" threw " + e + " at line #" + line); fail = true; } if (!list1.toString().equals(list2.toString())) { System.out.println("original list was changed"); fail = true; } testCount++; if (fail) { System.out.println("failed"); failCount++; } else { System.out.println("passed"); } System.out.println(); } }