问题
I wrote some code that returns the median of an unsorted odd numbered array, but it does not return the median of an even numbered array.
I know that in order to find the median of an even numbered array, you have to take the middle two numbers of the array, average them, and that's the median. I can't translate that into usable code. Aside from the obvious verbosity of this code, the issue seems to be with lines 7-8 and I don't see why.
I prefer hints to answers, but if you rather post some fixed code, I can accept that too.
def media(array)
sorted = array.sort
list = sorted.length
if list %2 != 0
(list + 1) / 2.0
else
even = ((list.to_f + 2) / 2) + ((list.to_f / 2)
return (even/2)
end
end
回答1:
I'm going to just jump in with a solution here...
def median(ary)
mid = ary.length / 2
sorted = ary.sort
ary.length.odd? ? sorted[mid] : 0.5 * (sorted[mid] + sorted[mid - 1])
end
Edit - I've incorporated .odd?
as per BroiSatse's suggestion.
回答2:
a = [1,2,4,5,3,6]
sorted = a.sort
list = sorted.length
if list %2 != 0
puts sorted[list/2]
else
puts (sorted[list/2]+sorted[(list/2)-1])/2.0
end
回答3:
def get_median(values)
quotient, remainder = values.sort!.length.divmod(2)
medians = [values[quotient], values[quotient-(remainder+1) % 2]].uniq
medians.length > 1 ? medians.map(&:to_f).reduce(:+) / 2 : medians[0]
end
This should work, but let me know if it does not.
edit forgot to add .to_f to medians values. Here is my testing in Pry.
[1] pry(main)> def get_median(values)
[1] pry(main)* quotient, remainder = values.sort!.length.divmod(2)
[1] pry(main)* medians = [values[quotient], values[quotient-(remainder+1) % 2]].uniq
[1] pry(main)* medians.length > 1 ? medians.map { |v| v.to_f }.reduce(:+) / 2 : medians[0]
[1] pry(main)* end
=> nil
[2] pry(main)> values = [1,2,3]
=> [1, 2, 3]
[3] pry(main)> get_median values
=> 2
[4] pry(main)> values << 4
=> [1, 2, 3, 4]
[5] pry(main)> get_median values
=> 2.5
[6] pry(main)> get_median values << -1
=> 2
[7] pry(main)> values
=> [-1, 1, 2, 3, 4]
[8] pry(main)> values << 11
=> [-1, 1, 2, 3, 4, 11]
[9] pry(main)> get_median values << -1
=> 2
[10] pry(main)> values
=> [-1, -1, 1, 2, 3, 4, 11]
[11] pry(main)> values.delete_if { |v| v == -1}
=> [1, 2, 3, 4, 11]
[12] pry(main)> values << -1
=> [1, 2, 3, 4, 11, -1]
[13] pry(main)> get_median values
=> 2.5
[14] pry(main)>
回答4:
Here is the answer:
def get_median(sub_a)
result = -1
size = sub_a.size
if size == 0
result = 0
elsif size == 1
result = sub_a[0]
elsif size == 2
result = get_average(sub_a[0], sub_a[1])
else
sorted_a = sub_a.sort
index = size / 2
if size % 2 == 0
result = get_average(sorted_a[index - 1], sorted_a[index]);
else
result = sorted_a[index];
end
end
'%0.01f' % result
end
来源:https://stackoverflow.com/questions/21487250/find-the-median-of-an-array