Java > AP-1 > scoresSpecial (CodingBat Solution)

Problem:

Given two arrays, A and B, of non-negative int scores. A "special" score is one which is a multiple of 10, such as 40 or 90. Return the sum of largest special score in A and the largest special score in B. To practice decomposition, write a separate helper method which finds the largest special score in an array. Write your helper method after your scoresSpecial() method in the JavaBat text area.

scoresSpecial({12, 10, 4}, {2, 20, 30}) → 40
scoresSpecial({20, 10, 4}, {2, 20, 10}) → 40
scoresSpecial({12, 11, 4}, {2, 20, 31}) → 20


Solution:

public int scoresSpecial(int[] a, int[] b) {
  int spec1 = helper(a);
  int spec2 = helper(b);
  return spec1 + spec2;
}

public int helper(int[] a) {
  int tmp = 0;
  for (int i = 0; i < a.length; i++) {
    if (a[i] % 10 == 0 && a[i] > tmp)
      tmp = a[i];
  }
  return tmp;
}

6 comments:

  1. public int scoresSpecial(int[] a, int[] b) {
    int sum = 0;
    int max = 0;
    int max1 = 0;
    for (int i = 0; i < a.length; i++) {
    if (a[i] > max && a[i] % 10 == 0) {
    max = a[i];
    }
    }
    for (int j = 0; j < b.length; j++) {
    if (b[j] > max1 && b[j] % 10 == 0) {
    max1 = b[j];
    }
    }

    sum = max + max1;
    return sum;
    }

    ReplyDelete
  2. public int scoresSpecial(int[] a, int[] b) {
    return max(a) + max(b);
    }
    private int max(int[] n) {
    int high = 0;
    for (int i = 0; i < n.length; i++) {
    if (n[i] > high && n[i] % 10 == 0) {
    high = n[i];
    }
    }
    return high;
    }

    ReplyDelete
  3. public int scoresSpecial(int[] a, int[] b) {
    return scoreHelper(a) + scoreHelper(b);
    }
    public int scoreHelper(int[] array)
    {
    int max = 0;
    for (int score: array)
    {
    if (score % 10 == 0 && score > max)
    {
    max = score;
    }
    }
    return max;
    }

    ReplyDelete
  4. With lambda:

    public int scoresSpecial(int[] a, int[] b) {
    return largest(a) + largest(b);
    }

    public int largest(int[] nums) {
    return Arrays.stream(nums)
    .filter(n -> n % 10 == 0)
    .reduce(Integer::max).orElse(0);
    }

    ReplyDelete
  5. Another way with Java Stream

    public int scoresSpecial(int[] a, int[] b) {
    return biggest(a) + biggest(b);
    }

    private int biggest(int[] arr) {
    return Arrays.stream(arr).filter(i -> i % 10 == 0).max().orElse(0);
    }

    or straight without a method.

    public static int scoresSpecial(int[] a, int[] b) {
    int firstArr = Arrays.stream(a).filter(i -> i % 10 == 0).max().orElse(0);
    int secondArr = Arrays.stream(b).filter(i -> i % 10 == 0).max().orElse(0);
    return Integer.sum(firstArr, secondArr);
    }

    ReplyDelete