1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

More efficient way of doing this? (java exercise)

  1. Jan 11, 2017 #1
    1. The problem statement, all variables and given/known data
    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]

    2. Relevant equations


    3. The attempt at a solution
    Code (Java):

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

     
    Is there a more efficient way of doing this without having to check the length of both arrays?
     
  2. jcsd
  3. Jan 12, 2017 #2

    mfb

    User Avatar
    2016 Award

    Staff: Mentor

    Can java increase the size of arrays easily? You could initialize an array, then add a[0] to it if a.length>0, then add b[0] to it if b.length>0.
     
  4. Jan 12, 2017 #3
    Is the bolded a hint ? Since arrays are of fixed lengths. I was just thinking as I was doing these challenges that writing a bunch of if statements felt a little too trivial and not challenging...
     
  5. Jan 13, 2017 #4

    mfb

    User Avatar
    2016 Award

    Staff: Mentor

    No, it was a question. I never worked with Java. I know some languages can do that easily (e.g. PHP, JS and python), while in some others it is not advisable (e.g. C++) or completely impossible.

    If an array cannot change size, your solution should be the easiest option.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted