Reputation: 45
I'm trying to write a method that takes two int [] as arguments and returns a new int [] which is filled in an alternating sequence from the two given arrays. Ex: given arrays [1,2,3] and [10,20,30] would return [1,10,2,20,3,30]. Any help would be great, thanks.
This is what I have right now:
public int [] alternate(int [] a, int [] b){
int[] c = new int[a.length + b.length]
for (int i = 0; i < c.length; i + 2){
c[i] = a[i];
c[i + 1] = b[i];
}
return c;
Upvotes: 3
Views: 936
Reputation: 44854
a
- assume a and b are same sizei
normallySo
public static int [] alternate(int [] a, int [] b){
int[] c = new int[a.length + b.length];
int counter = 0;
for (int i = 0; i < a.length; i++){
c[counter++] = a[i];
c[counter++] = b[i];
// or
//c[2 * i] = a[i];
//c[2 * i + 1] = b[i];
}
return c;
}
public static void main(String[] args) {
int[] a = {1,2,3} ;
int[] b = {10,20,30} ;
int[] test = alternate(a,b);
System.out.println(Arrays.toString(test));
}
[1, 10, 2, 20, 3, 30]
Upvotes: 4
Reputation: 1724
If a
and b
arrays are not of same length, you can use the following method
public static int[] alternate(int[] a, int[] b) {
int min, max;
int count = 0;
min = Math.min(a.length, b.length);
max = Math.max(a.length, b.length);
int c[] = new int[min+max];
for(int i=0; i<max; i++) {
if(i<min) {
c[count++] = a[i];
c[count++] = b[i];
}else {
if(a.length==min) {
c[count++] = b[i];
}else {
c[count++] = a[i];
}
}
}
return c;
}
Main test
public static void main(String[] args) {
int[] a = {1,2,3,4} ;
int[] b = {10,20,30} ;
int[] test = alternate(a,b);
System.out.println(Arrays.toString(test));
}
Output:
[1, 10, 2, 20, 3, 30, 4]
Upvotes: 1