/* Java class containing static methods that perform elementwise sum and ** difference upon on arrays of type int[] (i.e., arrays of int values). ** ** Author: R. McCloskey ** last updated : October 2022 */ public class ArrayUtils { /* Returns a new array each of whose elements is the sum of the ** corresponding elements in the two given arrays (a[] and b[]). ** (In case a.length and b.length differ, we imagine that the shorter ** array is "expanded" to the other one's length and that the "new" ** elements have value zero.) ** To be precise, the array returned, call it c[], has these properties: ** c.length == N ** c[i] == a[i] + b[i] for all i in 0..M-1, ** c[i] == a[i] for all i in M..a.length-1, and ** c[i] == b[i] for all i in M..b.length-1, ** where M = min(a.length, b.length) and N = max(a.length, b.length) */ public static int[] sumElementWise(int[] a, int[] b) { final int M = Math.min(a.length, b.length); final int N = Math.max(a.length, b.length); int[] c = new int[N]; // Sum elements at corresponding locations in a[] and b[] and place // result into corresponding location of c[]. for (int i=0; i != M; i++) { c[i] = a[i] + b[i]; } // Now copy into c[] the remaining elements of the longer array. for (int i=M; i != a.length; i++) { c[i] = a[i]; } for (int i=M; i != b.length; i++) { c[i] = b[i]; } return c; } /* Returns a new array each of whose elements is the difference of the ** corresponding elements in the two given arrays (a[] and b[]). ** (In case a.length and b.length differ, we imagine that the shorter ** array is "expanded" to the other one's length and that the "new" ** elements have value zero.) ** To be precise, the array returned, call it c[], has these properties: ** c.length == N ** c[i] == a[i] - b[i] for all i in 0..M-1, ** c[i] == a[i] for all i in M..a.length-1, and ** c[i] == b[i] for all i in M..b.length-1, ** where M = min(a.length, b.length) and N = max(a.length, b.length) */ public static int[] differenceElementWise(int[] a, int[] b) { final int M = Math.min(a.length, b.length); final int N = Math.max(a.length, b.length); int[] c = new int[N]; // Take difference of elements at corresponding locations in a[] and b[] // and place result into corresponding location of c[]. for (int i=0; i != M; i++) { c[i] = a[i] - b[i]; } // Now copy into c[] the remaining elements of the longer array. for (int i=M; i != a.length; i++) { c[i] = a[i]; } for (int i=M; i != b.length; i++) { c[i] = -b[i]; } return c; } } // end of class