Java > Array-1 > plusTwo (CodingBat Solution)

Problem:

Given 2 int arrays, each length 2, return a new array length 4 containing all their elements.

plusTwo({1, 2}, {3, 4}) → {1, 2, 3, 4}
plusTwo({4, 4}, {2, 2}) → {4, 4, 2, 2}
plusTwo({9, 2}, {3, 4}) → {9, 2, 3, 4}


Solution:

public int[] plusTwo(int[] a, int[] b) {
  int[] myArray = new int[4];
  myArray[0] = a[0];
  myArray[1] = a[1];
  myArray[2] = b[0];
  myArray[3] = b[1];
  
  return myArray;
}


10 comments :

  1. public int[] plusTwo(int[] a, int[] b) {
    int[] s = {a[0],a[1],b[0],b[1]};
    return s;
    }

    ReplyDelete
  2. public int[] plusTwo(int[] a, int[] b) {
    return new int[] {a[0], a[1], b[0], b[1]};
    }

    ReplyDelete
  3. public int[] plusTwo(int[] a, int[] b) {

    int[] c = new int[4];

    c[0]=a[0];
    c[1]=a[1];
    c[2]=b[0];
    c[3]=b[1];

    return c;
    }

    ReplyDelete
  4. This will work for arrays of any length.

    public int[] plusTwo(int[] a, int[] b) {
    int[] sum = new int[a.length + b.length];
    int i = 0;

    for(; i < a.length; i++) {
    sum[i] = a[i];
    }
    for(; i < b.length + a.length; i++) {
    sum[i] = b[i - a.length];
    }
    return sum;
    }

    ReplyDelete
  5. the shortest way

    public int[] plusTwo(int[] a, int[] b) {

    return new int[] {a[0],a[1],b[0],b[1]};

    }

    ReplyDelete
  6. public int[] plusTwo(int[] a, int[] b)
    {
    return new int[] {a[0], a[1],b[0], b[1]};
    }

    ReplyDelete
  7. public int[] plusTwo(int[] a, int[] b) {
    int[] connect = { a[0], a[1], b[0], b[1] };
    return connect;
    }

    ReplyDelete
  8. public int[] plusTwo(int[] a, int[] b) {
    int[] newArr = {a[0],a[1],b[0],b[1]};
    return newArr;
    }

    ReplyDelete
  9. public int[] plusTwo(int[] a, int[] b) {
    return new int[] {a[0],a[1],b[0],b[1]};
    }

    ReplyDelete
  10. public int[] plusTwo(int[] a, int[] b) {
    int[] arr=new int[]{a[0],a[1],b[0],b[1]};
    return arr;
    }

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact