Due: October 27th @ 10:00 pm
Purpose:
To practice working with mutable, parametrized structures and methods over them.
Programming Problem 1: (Algos.java)
In this problem we practice using ArrayLists to write methods. Since we can't modify the ArrayList class (and these will be algorithms), we will make all our methods static and put them in a class called Algorithms.
Part 1:
Design the following methods. Note: most (if not all) will need helper methods that use accumulators. Think about how best to approach each problem before you start coding and make sure you know exactly what the method should take/return (purpose statements).
- A method sum that computes the sum of a given ArrayList<Integer>. Note: you can return either int or Integer, your choice.
- A method product that computes the product of a given ArrayList<Double>. Note: you can return either double or Double, your choice.
- A void method reverse that reverses the order of elements in a given arbitrary ArrayList. Note: this method will be parameterized by the element type of the list. I.e.:
static <X> void reverse(...){ ... }There are several ways to implement this method... select the one that makes the most sense to you.
Part 2:
Here's an interface for predicates over arbitrary things (we've seen this several times now):// Represents a Predicate interface IPred<X>{ // Is this predicate true for the given item? boolean huh(X x); }
Use the IPred interface to design the void method removeIf that removes elements from a given ArrayList that satisfy (it returns true) the given IPred... like a mutating filter.
Note: this method will be parameterized by the element type of the list (and the type of things that the IChange works on).- Create a class for giraffes, including a field for neck height (in addition to other fields if you want). Then make a list of giraffes and run natural selection by removing giraffes that have a neck height lower than a certain value.
- Create a NotPred class (which implements IPred) which takes an IPred and returns the logical inverse of the given predicate (i.e. it returns true when the given predicate returns false, and visa versa). Use it to remove the long-necked giraffes from the list.
Programming Problem 2: (Sponge.java)
Complete the SpongeBob program from Lab #7.