// Program to test solutions to problem #6 on the cse143 midterm, fall 2011. // Fill in your solution to insertAt, then compile and run the program // note: this program doesn't test the exception that should be thrown import java.util.*; class ArrayIntList { public void insertAt(int index, int n, int value) { // fill in your solution here // you can also rename the parameters above } public void insertAt2(int index, int n, int value) { if (index < 0 || index > size || n < 0) throw new IllegalArgumentException(); for (int i = size - 1; i >= index; i--) elementData[i + n] = elementData[i]; for (int i = 0; i < n; i++) elementData[i + index] = value; size += n; } 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 Test6 { public static void main(String[] args) { for (int i = 0; i <= 10; i++) test(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, i); test(new int[] {}, 0); } public static void test(int[] data, int num) { ArrayIntList list1 = new ArrayIntList(); ArrayIntList list2 = new ArrayIntList(); for (int n : data) { list1.add(n); list2.add(n); } System.out.println("initial list = " + list1); for (int i = 0; i <= 3; i++) { int value = 100 + i; System.out.println("inserting " + i + " of " + value + " at " + num); list1.insertAt2(num, i, value); System.out.println("new list = " + list1); boolean fail = false; try { list2.insertAt(num, i, value); System.out.println("yours = " + list2); if (!list1.toString().equals(list2.toString())) { fail = true; } } catch (RuntimeException e) { System.out.println(" threw " + e); fail = true; } if (fail) System.out.println("failed"); else System.out.println("passed"); } System.out.println(); } }