Last active
December 15, 2015 07:49
-
-
Save ysadka/5225794 to your computer and use it in GitHub Desktop.
Write a method median which takes an Array of numbers as its input and returns the median value. You might want to look up the definition of "median."" For example, median([1,2,3]) # => 2
median([4.5, 0, -1]) # => 0
median([-100, 100]) # => 0.0
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(array) | |
sorted_array = array.sort | |
even_or_odd = array.length % 2 | |
odd = (sorted_array.length - 1) / 2 | |
median_odd = sorted_array[odd] | |
even = sorted_array.length / 2 | |
even_value1 = sorted_array[even] | |
even_value2 = sorted_array[even - 1] | |
median_even = (even_value1 + even_value2.to_f) / 2.0 | |
if even_or_odd == 1 | |
return "The median is #{median_odd}" | |
elsif even_or_odd == 0 | |
return "The median is #{median_even}" | |
else | |
"Error" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment