// This class contains several small examples of array manipulation. // Each is written as a method. The main method includes some sample // client code. import java.util.*; public class ArraySample3 { public static void main(String[] args) { int[] list1 = {12, 8, 4, 0, 208, 14, 42, 38, 72, 96, 102}; int[] list2 = {84, 42, 92, 96, 2, 4, 8, 0, 72, 302, 17, 408}; System.out.println("list1 = " + Arrays.toString(list1)); System.out.println("list2 = " + Arrays.toString(list2)); System.out.println("allEven(list1) returns " + allEven(list1)); System.out.println("allEven(list2) returns " + allEven(list2)); int[] sum = runningSum(list1); System.out.println("runningSum(list1) returns " + Arrays.toString(sum)); sum = runningSum(list2); System.out.println("runningSum(list2) returns " + Arrays.toString(sum)); int[] result1 = interleave(list1, list2); int[] result2 = interleave(list2, list1); System.out.println("interleave(list1, list2) = " + Arrays.toString(result1)); System.out.println("interleave(list2, list1) = " + Arrays.toString(result2)); } // Write a static method called allEven that takes an array of // integers as a parameter and that returns true if all the integers // are even and that returns false otherwise public static boolean allEven(int[] list) { for (int i = 0; i < list.length; i++) { if (list[i] % 2 != 0) { return false; } } return true; } // Write a static method called runningSum that takes an array of // integers as a parameter and that returns a new array that // contains the running sum of the numbers in the array (where the // i-th value of the new array is the sum of the first i values of // the original array) public static int[] runningSum(int[] list) { int[] result = new int[list.length]; if (list.length > 0) { result[0] = list[0]; for (int i = 1; i < list.length; i++) { result[i] = list[i] + result[i - 1]; } } /* alternative solution: int sum = 0; for (int i = 0; i < list.length; i++) { sum = sum + list[i]; result[i] = sum; } */ return result; } // Write a static method called interleave that takes two arrays of // integers as parameters and that returns a new array that contains // the result of interleaving the elements of the two arrays. Two // arrays are interleaved by taking elements in an alternating // fashion from the two lists (first value of first list, first // value of second list, second value of first list, second value of // second list, etc). If one list is longer than the other, ignore // the extra values. public static int[] interleave(int[] list1, int[] list2) { int min = Math.min(list1.length, list2.length); int[] result = new int[2 * min]; for (int i = 0; i < min; i++) { result[2 * i] = list1[i]; // put list1[i] into the result result[2 * i + 1] = list2[i]; // put list2[i] into the result } return result; } }