// Allison Obourn, CSE 142 // Array problems similar to problems on the final exam. import java.util.*; public class ArrayPractice { public static void main(String[] args) { int[] numbers = {3, 8, 6}; System.out.println(Arrays.toString(delta(numbers))); System.out.println(isUnique(numbers)); int[] numbers2 = {2, 4, 6, 4, 2}; System.out.println(isUnique(numbers2)); String[] b = {"a", "b", "c", "d"}; swapPairs(b); System.out.println(Arrays.toString(b)); } // Write a static method named delta that accepts an array of integers as a // parameter and returns a new array formed by inserting between each pair of // values the difference between those values. For example, given this array: // int[] numbers = {3, 8, 6}; The call of delta(numbers) should return the following // array: {3, 5, 8, -2, 6} // 0 -> 0 // 1 -> 2 // 2 -> 4 public static int[] delta(int[] numbers) { int[] newNumbers = new int[numbers.length * 2 - 1]; for(int i = 0; i < numbers.length - 1; i++) { int delta = numbers[i + 1] - numbers[i]; newNumbers[i * 2] = numbers[i]; newNumbers[i * 2 + 1] = delta; } newNumbers[newNumbers.length - 1] = numbers[numbers.length - 1]; return newNumbers; } // 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[] a) { int[] sums = new int[a.length]; if (a.length > 0) { sums[0] = a[0]; for(int i = 1; i < a.length; i++) { sums[i] = a[i] + sums[i - 1]; } } return sums; } // Write a static method called isUnique that takes an array of integers as // a parameter and that returns true if the values in the list are unique // and that returns false otherwise. The values in the list are considered // unique if there is no pair of values that are equal. // 4 2 45 1 23 1 2 67 --> false public static boolean isUnique(int[] numbers) { for(int i = 0; i < numbers.length - 1; i++) { for(int j = i + 1; j < numbers.length; j++) { if(numbers[i] == numbers[j]) { return false; } } } return true; } // Write a method named swapPairs that accepts an array of strings as a parameter // and switches the order of values in a pairwise fashion. Your method should switch // the order of the first two values, then switch the order of the next two, switch // the order of the next two, and so on. If there are an odd number of values, the final // element is not moved. // a b c d --> b a d c public static void swapPairs(String[] a) { for(int i = 0; i < a.length - 1; i += 2) { String temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; } } }