'Two arrays. create 3rd array by combining first element of first array with first element of second array and so on
I have two arrays in Java.
int[] arr1= {3,13,5}
int[] arr2={4,7,9}
I want to create a third array arr3 such that first element in arr1 becomes first element in arr3, first element in arr2 becomes second element in arr3, second in arr1 should become third in arr3 and so on like below
arr3={3,4,13,7,5,9}
Can someone help with this
Solution 1:[1]
Use below function to merge your arrays. If one array has extra elements, then these elements are appended at the end of the combined array.
/**
* Function to merge two arrays alternatively
* @param arr1: First array
* @param arr2: Second array
* @param array1Length: size of array 1
* @param array2Length: size of array 2
* @param arr3: Result array
*/
public static void alternateMerge(int arr1[], int arr2[],
int array1Length, int array2Length, int arr3[])
{
int i = 0, j = 0, k = 0;
// Traverse both arrays
while (i < array1Length && j < array2Length)
{
arr3[k++] = arr1[i++];
arr3[k++] = arr2[j++];
}
// Store remaining elements of first array
while (i < array1Length)
arr3[k++] = arr1[i++];
// Store remaining elements of second array
while (j < array2Length)
arr3[k++] = arr2[j++];
}
Above function can be called from main() as below -
public static void main(String args[]){
int arr1[] = {3, 13, 5};
int array1Length = arr1.length;
int arr2[] = {4, 7, 9};
int array2Length = arr2.length;
int arr3[] = new int[array1Length + array2Length];
alternateMerge(arr1, arr2, array1Length, array2Length, arr3);
System.out.println("Alternate Merged Array: ");
for(int i : arr3)
System.out.print(i + " ");
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rohan Jethwani |
