Lab Homework 7

You are to complete this homework before attending the eighth lab.

Solve chapter 7 exercise 15 (collapse, page 497). First solve it in PracticeIt. Remember that you have to construct a new array to be returned by the method and it has to be of an appropriate length, including dealing with both odd and even length arrays. This problem turns out to be easier to solve if you write a loop that traverses the original array, adding those values to the new array, rather than traversing the new array.

After you have solved it in PracticeIt, copy and paste the following code into jGRASP and copy your solution from PracticeIt into the program to complete it:

import java.util.*;

public class CollapseTest {
   public static void main(String[] args) {
      test(new int[] {7, 2, 8, 9, 4, 13, 7, 1, 9, 10});
      test(new int[] {1, 2, 3, 4, 5});
      test(new int[] {100, -100});
      test(new int[] {1, 2, 3});
      test(new int[] {1});
      test(new int[] {});
   }

   public static void test(int[] list) {
      System.out.println("Collapsing " + Arrays.toString(list));
      System.out.println("Result   = " + Arrays.toString(collapse(list)));
      System.out.println();
   }

   // include your solution to the collapse method here
}

Working on this problem will help prepare you for the homework assignment. Remember that for these warm-up exercises you can talk to each other about how to solve it and even look at each other's solutions. Then you should work on the weekly programming assignment by yourself.