Java > Array-1 > start1 (CodingBat Solution)

Problem:

Start with 2 int arrays, a and b, of any length. Return how many of the arrays have 1 as their first element.

start1({1, 2, 3}, {1, 3}) → 2
start1({7, 2, 3}, {1}) → 1
start1({1, 2}, {}) → 1


Solution:

public int start1(int[] a, int[] b) {
int count = 0;
  if (a.length != 0) {
     if (a[0]== 1) count++; }
  if (b.length != 0) {
     if (b[0]== 1) count++; }
     
     return count;
}


8 comments :

  1. public int start1(int[] a, int[] b) {
    int result = 0;
    if (a.length > 0 && a[0] == 1)
    result++;
    if (b.length>0 && b[0]== 1)
    result++;
    return result;
    }

    ReplyDelete
  2. 2-Line Solution:

    public int start1(int[] a, int[] b) {
    int[][] ab = {a,b};
    return (int)Arrays.stream(ab).filter(arr -> arr.length > 0 && arr[0] == 1).count();
    }

    ReplyDelete
  3. Start with 2 int arrays, a and b, of any length. Return how many of the arrays have 1 as their first element.
    how to do it?

    ReplyDelete
  4. This is great, but I have a questions about the (int) in this solution: Is the "(int)" used to specify that this will be a stream of ints? Or is it telling stream that this is an array of ints? Thanks

    ReplyDelete
  5. public int[] biggerTwo(int[] a, int[] b) {
    int sumA = a[0]+a[1];
    int sumB = b[0]+b[1];
    if(sumA<sumB)
    return b;
    else
    return a;

    }

    ReplyDelete
    Replies
    1. bro your answer is not correct. and you answered completely different questions.

      Delete
  6. public int start1(int[] a, int[] b) {
    int one = 0;
    if(a.length != 0 && a[0]==1)
    {
    one++;
    }
    if(b.length != 0 && b[0]==1)
    {
    one++;
    }
    return one;
    }

    ReplyDelete
  7. public int start1(int[] a, int[] b) {
    int count = 0;
    int[][] arrays = new int[][]{a, b};
    for(int i = 0; i < arrays.length; i++) {
    if(arrays[i].length > 0 && arrays[i][0] == 1) {
    count++;
    }
    }
    return count;
    }

    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