Created
June 13, 2013 12:59
-
-
Save Antti/5773468 to your computer and use it in GitHub Desktop.
median & quartile
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def median_split(arr) | |
c = arr.size%2 | |
subset = [arr[0..arr.size/2-1], arr[arr.size/2+c..-1]] | |
m = median arr | |
subset[0].push m | |
subset[1].unshift m | |
subset | |
end | |
def median(arr) | |
if arr.size.odd? | |
arr[arr.size/2] | |
else | |
(arr[arr.size/2 -1 ].to_f + arr[arr.size/2].to_f) / 2 | |
end | |
end | |
def quartile(arr,n=3) | |
arr.sort! | |
split = median_split arr | |
case n | |
when 1 | |
median split[0] | |
when 2 | |
median arr | |
when 3 | |
median split[1] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment