Reputation: 43
I have been trying to solve the problem with the following algorithm but it does not work.
import java.util.Scanner;
import java.lang.Math;
public class AlterConcatenateArrays {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.println("How many elements do you want the first array have?");
int N = s.nextInt();
s.nextLine();
System.out.println("How many elements do you want the second array have?");
int M = s.nextInt();
int[] a = new int[N];
int[] b = new int[M];
System.out.println("The elements of the first array are: ");
for (int i = 0; i < N; i++) {
a[i] = (int) (Math.random() * 20);
System.out.print(a[i] + " \n");
}
System.out.println("The elements of the second array are: ");
for (int i = 0; i < M; i++) {
b[i] = (int) (Math.random() * 20);
System.out.print(b[i] + " \n");
}
System.out.println("Now we are going to concatenate the arrays by alternatingly choosing");
int[] c = new int[N + M];
for (int i = 0; i < ((N + M) / 2); i++) {
a[i] = c[2 * i + 0];
b[i] = c[2 * i + 1];
}
System.out.println("The new array is: ");
for (int i = 0; i < N + M; i++) {
System.out.print(c[i] + "\t");
}
}
}
The output of this program is this:
How many elements do you want the first array have?
2
How many elements do you want the second array have?
3
The elements of the first array are:
17
18
The elements of the second array are:
6
14
15
Now we are going to concatenate the arrays by alternatingly choosing
The new array is:
0 0 0 0 0
Upvotes: 0
Views: 984
Reputation: 29
//Program to merge alternate elements of 2 Arrays of same or different length
public class MergeAlternateElements {
public static void mergeAlternateElements(int[] a, int[] b) {
int n = a.length, m = b.length;
int mergedArray[] = new int[n + m];
int p = 0;
int i = 0;
for (i = 0; i < n; i++) {
mergedArray[p] = a[i];
p++;
if (i < m) {
mergedArray[p] = b[i];
p++;
}
}
if (n < m) {
System.arraycopy(b, i, mergedArray, p, m - n);
}
System.out.println("Merged Array:");
for (int k : mergedArray)
System.out.print(k + " ");
}
public static void main(String[] args) {
int[] a = { 24, 2, 45, 20, 56, 75, 21, 56, 99, 53 };
int b[] = { 112, 234, 500, 123, 432, 567, 787, 909, 808, 600, 678, 900};
mergeAlternateElements(b, a);
System.out.println();
mergeAlternateElements(a, b);
}
}
Upvotes: 0
Reputation: 61
Hello
c array is initialized with zeros implicitly. And in the for cycle, I think, you want to fill up the c array, not a and b.
Upvotes: 0
Reputation: 82
Remember the difference between L value and R value. Always important in programming
a[i] = c[2*i+0];
b[i] = c[2*i+1];
This is wrong
Upvotes: 0
Reputation: 201497
You've swapped the assignments here.
{
a[i] = c[2*i+0];
b[i] = c[2*i+1];
}
should be assigning into c
from a
and b
like
{
c[2*i+0] = a[i];
c[2*i+1] = b[i];
}
Upvotes: 4