Skip to content

Instantly share code, notes, and snippets.

@tmcw
Created February 25, 2013 23:23
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmcw/5034285 to your computer and use it in GitHub Desktop.
Save tmcw/5034285 to your computer and use it in GitHub Desktop.
median, literate coffeescript edition
// Generated by CoffeeScript 1.5.0
(function() {
var median;
median = function(x) {
var sorted;
if (x.length === 0) {
return null;
}
sorted = x.slice().sort(function(a, b) {
return a - b;
});
if (sorted.length % 2 === 1) {
return sorted[(sorted.length - 1) / 2];
} else {
return (sorted[(sorted.length / 2) - 1] + sorted[sorted.length / 2]) / 2;
}
};
}).call(this);

median is the 'middle number' of a list. often medians are useful when the list contains extreme values and the average would be skewed by outliers

median = (x) ->

The median of an empty list is null

    return null if (x.length == 0)

Sorting the array makes it easy to find the center, but use .slice() to ensure the original array x is not modified

    sorted = x.slice().sort((a, b) -> a - b)

If the length of the list is odd, the median is the central number

    if (sorted.length % 2 == 1)
        sorted[(sorted.length - 1) / 2]
    else

Otherwise, the median is the average of the two numbers at the center of the list

        (sorted[(sorted.length / 2) - 1] +
        sorted[(sorted.length / 2)]) / 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment