Search code examples
javaapache-commons-math

Calculate average top third of the population


Could you guys help me which apache-commons-math classes can I use to calculate the average of the top third of the population.

To calculate the average I know can use org.apache.commons.math3.stat.descriptive.DescriptiveStatistics.

How to get the top third of the population?

Example

Population: 0, 0, 0, 0, 0, 1, 2, 2, 3, 5,14

Top third: 2, 3, 5, 14

Average = 24/4= 6.0


Solution

  • First of all what do you call top third of population? If set is divides by 3 and remainder is 0, then its is simple, but in your case 11%3 = 2. So You should know how to get top third when remainder is not equal 0.

    I would suggest You to use Arrays procedures, to get Top third of set. If You still want to use DescriptiveStatistics you can invoke it.

        double[] set = {0, 0, 0, 0, 0, 1, 2, 2, 3,4,5};
    
        Arrays.sort(set);
    
        int from = 0;
        if (set.length % 3==0){
            from = set.length/3*2 ;
        }
        if (set.length % 3 != 0){
            from = Math.round(set.length/3*2) + 1;
        }
    
        double [] topThirdSet = Arrays.copyOfRange(set,from , set.length);
        DescriptiveStatistics ds = new DescriptiveStatistics(topThirdSet);
        System.out.println(ds.getMean());