Java > Array-1 > biggerTwo (CodingBat Solution)

Problem:

Start with 2 int arrays, a and b, each length 2. Consider the sum of the values in each array. Return the array which has the largest sum. In event of a tie, return a.

biggerTwo({1, 2}, {3, 4}) → {3, 4}
biggerTwo({3, 4}, {1, 2}) → {3, 4}
biggerTwo({1, 1}, {1, 2}) → {1, 2}


Solution:

public int[] biggerTwo(int[] a, int[] b) {
  if (b[1] + b[0] > a[1] + a[0])
  return b;
  else
  return a;
}


8 comments :

  1. Thats the algorithm for any size of an array:


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


    int temp;
    int temp2;
    int sum=0;
    int sum1=0;

    int [] x = new int [a.length];
    int [] z = new int [b.length];


    for(int i=0;isum1)
    return a;

    if(sum==sum1)
    return a;

    else
    return b;

    }

    ReplyDelete
  2. Best and easiest way:

    public int[] biggerTwo(int[] a, int[] b) {
    int sum1 = 0;
    int sum2 = 0;

    for(int x : a){
    sum1 = sum1 + x;
    }

    for(int y : b){
    sum2 = sum2 + y;
    }

    if(sum1 >= sum2){
    return a;
    } else {
    return b;
    }
    }

    ReplyDelete
  3. public int[] biggerTwo(int[] a, int[] b) {
    int aVal = a[0] + a[1];
    int bVal = b[0] + b[1];
    if(aVal == bVal) return a;
    return aVal > bVal ? a:b;
    }

    ReplyDelete
  4. public int[] biggerTwo(int[] a, int[] b) {
    int i=0;
    int sum=0;
    int j=0;
    int sum2=0;
    while(i=sum2)
    return a;
    else
    return b;


    }

    ReplyDelete
  5. public int[] biggerTwo(int[] a, int[] b) {
    int i=0;
    int sum=0;
    int j=0;
    int sum2=0;
    while(i=sum2)
    return a;
    else
    return b;


    }

    ReplyDelete
  6. public int[] biggerTwo(int[] a, int[] b) {
    int sum = a[0]+a[1];
    int summ = b[0]+b[1];
    if(sum==summ)
    return a;
    if(sum>summ)
    return a;
    else
    return b;
    }

    ReplyDelete
  7. public int[] biggerTwo(int[] a, int[] b) {
    if(a[0]+a[1]>b[0]+b[1] || a[0]+a[1]==b[0]+b[1])
    return a;
    return b;
    }

    ReplyDelete
  8. public int[] biggerTwo(int[] a, int[] b) {
    int sumA = Arrays.stream(a).sum();
    int sumB = Arrays.stream(b).sum();

    if(sumA < sumB){
    return b;
    } else {
    return a;
    }
    }

    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