Forked from dbc-challenges/phase0_template_gist.rb
Last active
January 3, 2016 00:09
-
-
Save carolineartz/b9d18840264153815e3e to your computer and use it in GitHub Desktop.
Exercise: Calculating the median of an array of numbers
Write a method median which takes an Array of numbers as its input and returns the median value.
This file contains hidden or 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
# CALCULATE THE MEDIAN OF AN ARRAY OF NUMBERS | |
# PSEUDOCODE | |
# INPUT: array of numbers | |
# OUPUT: the median number of the elements of the input array | |
# STEPS: sort the array | |
# determine if the array has one or two middle values by checking | |
# if the length is even or odd | |
# if there is an odd length, return the value of the middle element | |
# otherwise return the average of the two middle elements' values | |
# INITIAL CODE: | |
def median(array) | |
array.sort! | |
n = array.length | |
if n % 2 != 0 | |
return array[(n - 1) / 2] | |
else | |
return (array[n/2] + array[(n/2)-1]) / 2.0 | |
end | |
end | |
# REFACTORED CODE: | |
def median(array) | |
mid = array.length / 2 | |
if array.length.odd? | |
array.sort![mid] | |
else | |
(array.sort![mid - 1] + array[mid]) / 2.0 | |
end | |
end | |
# REVIEW/REFLECT My approach for this problem was pretty solid, I believe. I | |
# can't figure out much more to refactor; most solutions I have found within | |
# DBC and outside have pretty simliar logic and use of methods. I did find out | |
# about this little #odd? method, and its complement #even?, and now I can | |
# avoid using the modulus technique for testing even/odd. I'll have to | |
# remember these! | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment