简体   繁体   中英

Calculating average without highest and lowest values in an array

So I am trying to calculate the average and sum of an array, however I have to remove the highest and lowest values before I can calculate the avg/sum.

I have code to fill the array with random doubles, and then find the highest and lowest value.

What I am unsure about is if there is a way to subtract the highest and lowest values or if I have to copy the data from the array into a new one minus the highest and lowest values and then calc the avg/sum.

This is what I have so far. Forgive me if this is somewhat obvious but I am stumped, and still in an intro to java course.

Here is my code so far.

double [] contestantOne = new double[8];

for (int index=0; index < contestantOne.length; index++) {
    contestantOne [index] = (double) (Math.random()*9) + 1;
}

for (int index=0; index < contestantOne.length; index++) {
    System.out.println( contestantOne [index] + "\n");
}

double contestantOneHigh; contestantOneHigh = contestantOne[0];

for (int index=1; index <contestantOne.length; index++) {    
    if (contestantOne[index] > contestantOneHigh)
        contestantOneHigh = contestantOne[index];
}

System.out.print("The highest value in your array is" 
               + " " + contestantOneHigh);
System.out.println();
System.out.println();

double contestantOneLow; contestantOneLow = contestantOne[0];
for (int index=1; index<contestantOne.length; index++) {   

    if (contestantOne [index] < contestantOneLow)
        contestantOneLow = contestantOne[index];
}    

System.out.print("The lowest value in your array is"
               + " " + contestantOneLow);
System.out.println();
System.out.println();

Calculate the sum like you normally would, but keep a variable each for the min and max, subtracting them out at the end:

double min, max, sum;
min = max = sum = list[0];  // May want to add a check to make sure length > 1
for(int i = 1; i < list.length; i++) {
    double thisValue = list[i];
    sum += thisValue;
    min = Math.min(min, thisValue);
    max = Math.max(max, thisValue);
}
sum -= min + max;
double avg = sum / (list.length - 2);

Of course you may need to adjust the precise methods to suit the class you're using.

if you are going to calculate the average of an array of values, and you do not know if you will have zeros in it. I used:

        int[] arrayDays = new int[] {monday,tuesday,wednesday,thursday,friday,saturday,sunday};
    int totalValue = 0;
    int divide = 0;

    for (int i=0;i<arrayDays.length;i++){
        if (arrayDays[i] != 0){
            totalValue = totalValue + arrayDays[i];
            divide = divide+1;
        }
    }
    Float average = 0f;
    if (divide!=0){
        average = Float.valueOf(totalValue / divide);
    }

Why don't you use a TreeSet instead of an array? This way, the elements are going to be sorted and you will be able to remove the higher and lowest elements with O(1) complexity instead of going through the whole array.

You will only have to go through the collection to make the sum, and that's all. Your whole program will run in O(logn) + O(n) time.

public static void main(String[] args) {
    TreeSet<Double> contestantOne = new TreeSet<>();

    for (int index=0; index < 8; index++) {
        contestantOne.add((double) (Math.random()*9) + 1);
    }

    Iterator<Double> iterator = contestantOne.iterator();
    while(iterator.hasNext()){
        System.out.println(iterator.next());
    }

    double contestantOneHigh = contestantOne.pollLast();

    System.out.print("The highest value in your array is" 
                   + " " + contestantOneHigh);


    double contestantOneLow = contestantOne.pollFirst();

    System.out.println("The lowest value in your array is"
                   + " " + contestantOneLow);

    double sum = 0.0;
    iterator = contestantOne.iterator();

    while(iterator.hasNext()){
        sum += iterator.next();
    }

    System.out.println("The sum excluding first and last is: " + sum);
    System.out.println("The average excluding first and last is: " + sum/contestantOne.size());
}

traverse the array again checking if each element is equal to contestantOneLow/High, if it's not add to count, when you done divide this by contestantOne.length - 2 or just contestantOne.length. that should give you your avg.

I don't understand why you need to remove the high and low value from the array to get the average? The average should be the sum of all values divided by the total number of values:

double sum = 0;
for (int index=0; index < contestantOne.length; index++)
{
    //If you really need to remove highest and lowest value
    if (contestantOne[index] != contestantOneLow && contestantOne[index] != contestantOneHigh)
        sum += contestantOne[i];
}
double avg = sum / (double)(contestantOne.length - 2);

The problem with removing the values as done above, is if your array highs and lows aren't unique (array[10, 13, 15, 3, 15, 3, 6] 15 = High, 3 = Low) then your average will be incorrect when you calculate it because it will ignore both 15s and 3s.

I would suggest storing the index of high and index of low and using that instead.

Arrays.sort(a);
find sum of array a
sum -= a[0] + a[a.length - 1]
return sum / (a.length - 2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM