Skip to content

Instantly share code, notes, and snippets.

@Stephenitis
Forked from mattdvhope/gist:6043860
Last active December 20, 2015 00:49
Show Gist options
  • Save Stephenitis/6044256 to your computer and use it in GitHub Desktop.
Save Stephenitis/6044256 to your computer and use it in GitHub Desktop.
# Median of an array of numbers
def median(array)
array.each do |element|
if (array.length/2).to_f == (array.length.to_f)/2
element_even = element.to_i
median_value = (element_even[(array.length/2)].to_f + element_even[(array.length/2) + 1].to_f) / 2
else
element_odd = element.to_i
median_value = element_odd[(array.length/2) + 1].to_i
end
end
#your method returns here, your .each will return the entire array when it is done iterating over your array.
end
array1 = [1, 2, 3, 4, 5, 5, 7]
puts array1.inspect
puts "Median is " + median(array1).to_s
array2 = [4, 4, 5, 5, 6, 6, 6, 7]
puts array2.inspect
puts "Median is " + median(array2).to_s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment