Java > Array-2 > centeredAverage (CodingBat Solution)

Problem:

Return the "centered" average of an array of ints, which we'll say is the mean average of the values, except ignoring the largest and smallest values in the array. If there are multiple copies of the smallest value, ignore just one copy, and likewise for the largest value. Use int division to produce the final average. You may assume that the array is length 3 or more.

centeredAverage({1, 2, 3, 4, 100}) → 3
centeredAverage({1, 1, 5, 5, 10, 8, 7}) → 5
centeredAverage({-10, -4, -2, -4, -2, 0}) → -3

Solution:

public int centeredAverage(int[] nums) {
int min = nums[0];
int max = nums[0];
int sum = 0;

for (int i = 0; i < nums.length; i++){
sum += nums[i];
min = Math.min(min,nums[i]);
max = Math.max(max,nums[i]);
}
sum = sum - max - min;
sum = sum / (nums.length-2);
return sum;

}


1 comment :

  1. public int centeredAverage(int[] nums) {
    int av = 0;
    Arrays.sort(nums);
    for (int i = 1; i < nums.length-1; i++)
    {
    av += nums[i];

    }
    return av/(nums.length-2);

    }

    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