Java Dailly Tip: Create an array from two arrays and combine elements
Problem
I got a recruitment request for two arrays. Here it is. Assuming I have two arrays in Java:
int[] firstArray = {3,13,5} int[] secondArray ={4,7,9}
I want to create the third array so that the first element in the first array becomes the first element in the third array, and the first element in the second array becomes the second element in the first array, and so on. Here is an example:
int[] thirdArray = {3,4,13,7,5,9}
Jak to zrobić?
Solution
Use the function below to merge your arrays. If one array has additional elements, those elements are appended to the end of the joined array.
private static int[] mergeArrays( int firstArray[], int secondArray[], int firstArrayLength, int secondArrayLength ){ int mergedArray[] = new int[firstArrayLength + secondArrayLength]; int i = 0, j = 0, k = 0; // Traverse both arrays while (i < firstArrayLength && j < secondArrayLength) { mergedArray[k++] = firstArray[i++]; mergedArray[k++] = secondArray[j++]; } // Store remaining elements of first array while (i < firstArrayLength) mergedArray[k++] = firstArray[i++]; // Store remaining elements of second array while (j < secondArrayLength) mergedArray[k++] = secondArray[j++]; return mergedArray; }
The above function can be called from main() as below:
public static void main(String args[]){ int firstArray[] = {3, 13, 5}; int firstArrayLength = firstArray.length; int secondArray[] = {4, 7, 9}; int secondArrayLength = secondArray.length; System.out.println("Alternate Merged Array: "); for(int i : mergeArrays(firstArray, secondArray, firstArrayLength, secondArrayLength)) System.out.print(i + " "); }