Rick Meyers
Rick Meyers

Reputation: 45

Creating an alternating array method in java, can you tell me where I'm going wrong?

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

Answers (2)

Scary Wombat
Scary Wombat

Reputation: 44854

  1. Missing semicolon
  2. Increment only to length of a - assume a and b are same size
  3. Have counter to keep track of where new elements are inserted, or use idea as per @ErwinBolwidt
  4. increment i normally
  5. Note to self to test code before posting

So

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; 
}

Main Test:

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));
}

Console Output:

[1, 10, 2, 20, 3, 30]

Upvotes: 4

Azhar Zafar
Azhar Zafar

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

Related Questions