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) {
     Arrays.sort(nums);
     int count = 0;
     int sum = 0;
     for (int i = 1; i < nums.length - 1; i++){
     sum += nums[i];
     count++;}
     return sum / count;
}



7 comments :

  1. M not getting it...
    The question is saying that if u have more than one copies of max or min nums then just escape only one copy and include others to find avg.
    how to do that ?

    ReplyDelete
    Replies
    1. with out built in function

      public int centeredAverage(int[] nums) {
      int max,min,sum;
      max=min=nums[0];
      sum=0;
      for(int i=0;inums[i])?nums[i]:min);
      max=((max<nums[i])?nums[i]:max);
      }

      return (sum-max-min)/(nums.length-2);
      }

      Delete
  2. ohhhh got it... u r sorting the array.;)

    ReplyDelete
  3. public int centeredAverage(int[] nums) {
    int sum = 0;
    int largest = nums[0];
    int smallest = nums[0];

    for (int i = 0; i < nums.length; i++) {

    smallest = Math.min(smallest, nums[i]);
    largest = Math.max(largest, nums[i]);

    sum = sum + nums[i];
    }

    sum = sum - largest;
    sum = sum - smallest;

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

    ReplyDelete
  4. public int centeredAverage(int[] nums) {

    int temp = 0;
    int min = nums[0];
    int max = nums[0];

    for(int i = 0; imax){
    max = nums[i];
    }

    temp = temp+nums[i];

    }

    int tempo = temp-max-min;
    int size = nums.length-2;
    int avg = tempo/size;

    return avg;

    }

    ReplyDelete
  5. public int centeredAverage(int[] nums) {
    Arrays.sort(nums);
    return (nums.length%2 == 0) ? (nums[nums.length/2 - 1] + nums[nums.length/2])/2 : nums[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