Task: Given two int arrays array1 and array2 of the same length, zip should return an array that's twice as long, in which the elements of array1 and array2 are interleaved. That is, element #0 of the result array is array1[0], element #1 is array2[0], element #2 is array1[1], element #3 is array2[1], and so on.
public static int [] zip(int [ ] array1, int [] array2) {
//make sure both arrays have same length
if (array1.length != array2.length) {
throw new IllegalArgumentException("Unequal array lengths - zip not possible");
}
int [] zippedArray = new int [array1.length+ array2.length];
int idx_1 = 0;
int idx_2 = 0;
//for each element of first array, add to new array if index of new array is even
for (int i=0; i < zippedArray.length; i+=2){
zippedArray[i]= array1[idx_1++];
}
for (int i=1; i < zippedArray.length; i+=2){
zippedArray[i]= array2[idx_2++];
}
//check contents of new array
for (int item: zippedArray){
System.out.print(item + " ");
}
return zippedArray;
}