In this exercise, we are going to write some static methods which perform operations on arrays. The skeleton for the class is
public class ArrayOps { public static double findMax(double[] data) { // ADD CODE HERE } public static double[] normalise(double data[]) { // ADD CODE HERE } public static void normaliseInPlace(double data[]) { // ADD CODE HERE } public static double[] reverse(double[] data) { // ADD CODE HERE } public static void reverseInPlace(double[] data) { // ADD CODE HERE } public static void swap(double[] data1, double[] data2) { // ADD CODE HERE } }
You may find it useful to write a main() method for testing your class, although it is not required.
The desired behavour of the methods is described below. All of them take input arrays of type double[].
- findMax() should find and return the largest value in an array.
- normalise() should ensure that the sum of the elements in the array is 1.0, whilst maintaining the relative sizes of the elements. This is done by finding the sum of the array, and then dividing each element by this number.
- reverse() should reverse the order of elements of the array.
Note that there are two versions of the methods normalise() and reverse(). In the first version, your code should create a new array newA, perform the operation on newA without modifying the original input array, and return newA as value. In the second version of these methods, there is no return value. Instead the methods perform the operations ‘in-place’ on the input array.
- swap() should swap the contents of data1 with the contents of data2. (You can assume the arrays are the same length.) Again, this modification is carried out ‘in-place’.
An automated test has been created for this exercise: ArrayOpsTest.java.