Java > Array-1 > front11 (CodingBat Solutions)

Problem:

Given 2 int arrays, a and b, of any length, return a new array with the first element of each array. If either array is length 0, ignore that array.

front11({1, 2, 3}, {7, 9, 8}) → {1, 7}
front11({1}, {2}) → {1, 2}
front11({1, 7}, {}) → {1}


Solution:

public int[] front11(int[] a, int[] b) {
  if (a.length == 0 && b.length == 0)
  return new int[] {};
  
  else if (a.length !=0 && b.length == 0)
  return new int[]{a[0]};
  
  else if (a.length == 0 && b.length != 0)
  return new int[]{b[0]};
  else
  return new int[] {a[0],b[0]};
}


6 comments :

  1. public int[] front11(int[] a, int[] b) {
    int[] c=new int[a.length>0?b.length>0?2:1:b.length>0?1:0];
    if(a.length>0){c[0]=a[0];}
    if(b.length>0){c[a.length>0?1:0]=b[0];}
    return c;
    }

    ReplyDelete
    Replies
    1. public int[] front11(int[] a, int[] b) {
      if(a.length>=1&&b.length>=1)
      return new int[] {a[0],b[0]};
      if(a.length>1&&b.length<1)
      return new int[] {a[0]};
      if(a.length<1&&b.length>1)
      return new int[] {b[0]};

      return a;
      }

      Delete
  2. public int[] front11(int[] a, int[] b) {
    return
    a.length >= 1 && b.length >= 1 ? new int[] {a[0], b[0]} :
    a.length >= 1 ? new int[] {a[0]} : b.length >= 1 ? new int[] {b[0]} : new int[0];
    }

    ReplyDelete
  3. public int[] front11(int[] a, int[] b) {
    if (b.length==0 && a.length==0){
    return new int [] {};
    }

    if (a.length==0){

    return new int [] {b[0]};

    }
    if (b.length==0){

    return new int [] {a[0]};
    }

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

    ReplyDelete
  4. FASTEST AND EASIEST:

    public int[] front11(int[] a, int[] b) {
    if(a.length >= 1 && b.length >= 1){
    return new int[] {a[0], b[0]};
    } else if(a.length == 0 && b.length >= 1) {
    return new int[] {b[0]};
    } else if (a.length >= 1 && b.length == 0){
    return new int[] {a[0]};
    } else {
    return new int[] {};
    }
    }

    ReplyDelete
    Replies
    1. public int[] front11(int[] a, int[] b) {
      return (a.length>0 && b.length == 0)?new int[] {a[0]}:
      (a.length==0 && b.length>0)?new int[] {b[0]}:
      (a.length>0 && b.length>0)?new int[] {a[0], b[0]}:
      new int[] {};
      }

      Delete

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