Groovy web console

subscribe to the feed Subscribe
to this
site
median + percentile (via #groovywebconsole)
tweet this snippet Tweet
this
script

median + percentile

Published 7 months ago by danrask
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
double median(long[] numbers) {
    Arrays.sort(numbers, 0, numbers.length);
    int middle = numbers.length / 2;
    if (numbers.length % 2 == 1) {
        return numbers[middle];
    } else {
        return (numbers[middle - 1] + numbers[middle]) / 2.0;     
    }   
}

long[] percentiles(long[] numbers, double... percentiles) {
    Arrays.sort(numbers, 0, numbers.length);
    long[] values = new long[percentiles.length];
    for (int i = 0; i < percentiles.length; i++) {
        int index = (int) (percentiles[i] * numbers.length);
        values[i] = numbers[index];
    }     
    return values;   
}

long[] numbers = [1, 2, 3, 4, 5];

println(median(numbers))
println(percentiles(numbers, 0.6));