Last active
December 28, 2015 03:39
-
-
Save jedschneider/7436695 to your computer and use it in GitHub Desktop.
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
# original solution in ruby tapas 150 | |
class Median | |
def self.avdi(list) | |
sorted = list.sort | |
q, r = sorted.size.divmod(2) | |
middle = sorted[q - 1 + r, 2 - r] | |
middle.reduce(:+) / middle.size | |
end | |
def self.jed(list) | |
list = list.sort | |
length = list.size / 2 | |
# create two arrays one going up one going down | |
last_half = list.slice(length..-1).reverse | |
first_half = list.take(length) | |
# tuples are the complimentary positions in each array | |
tuples = last_half.zip(first_half) | |
# the last tuple either has [number, nil] or [number, number] | |
# we abstract away the conditional using list processing | |
res = tuples.last.compact | |
res.reduce(:+) / res.length | |
end | |
end | |
arr1 = [1,2,3,4,5,6,7,8,9] | |
arr2 = [1,2,3,4,5,6,7,8,9,10] | |
puts Median.jed(arr1) | |
puts Median.avdi(arr1) | |
puts Median.jed(arr2) | |
puts Median.avdi(arr2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment