0

I'm working through Java problems on codingbat.com, and have come to a halt at this one, scoresAverage. As the exercise description is a bit complicated, I will simply just paste it here:

Given an array of scores, compute the int average of the first half and the second half, and return whichever is larger. We'll say that the second half begins at index length/2. The array length will be at least 2. To practice decomposition, write a separate helper method
int average(int[] scores, int start, int end) { which computes the average of the elements between indexes start..end. Call your helper method twice to implement scoresAverage(). Write your helper method after your scoresAverage() method in the JavaBat text area. Normally you would compute averages with doubles, but here we use ints so the expected results are exact.

The code I have so far does not return any errors, but the numbers it returns are not correct. Can anyone help me with this? My code attempt is as follows:

public int scoresAverage(int[] scores) {
  int mid = scores.length/2;

  int average1 = average(scores, 0, mid);
  int average2 = average(scores, mid, scores.length);

  return Math.max(average1,average2); 
}


public int average(int[] scores, int start, int end){
  int sum = 0;
  for (int i=start; i<end; i++){
    sum += scores[i];
  }
  return sum/(scores.length);
}

2 Answers 2

4

sum/scores.length would average the sum of ALL of the numbers; you want sum/(end - start) to average a sum of the subset of the numbers

3
  • 1
    I would make sum a float/double type and then return a rounded value. Because like this, an average of (as double) 2.9 would be returned as 2 instead of 3!
    – MalaKa
    Apr 12, 2013 at 14:03
  • @MalaKa This looks like a school assignment, and since rounding was not specified the professor probably does not want doubles to be used in the computation.
    – NominSim
    Apr 12, 2013 at 14:05
  • @NominSim I see your point, I thought about that, too. But still, it doesn't make a lot sense to me.. But yeah, it might be desired to only use integers..
    – MalaKa
    Apr 12, 2013 at 14:11
0

This will get the average of each half:

return sum/(scores.length/2) 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.