ruby 练习:计算数字数组的中位数写一个方法中位数,它取一个数字数组作为输入并返回

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 练习:计算数字数组的中位数写一个方法中位数,它取一个数字数组作为输入并返回相关的知识,希望对你有一定的参考价值。

# 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!


以上是关于ruby 练习:计算数字数组的中位数写一个方法中位数,它取一个数字数组作为输入并返回的主要内容,如果未能解决你的问题,请参考以下文章

ruby 练习:计算数组totalWrite一个方法总计,它将一个数字数组作为输入并返回它们的总和(总和)。

机试练习08:poj3784——动态堆求解中位数

查找中位数而不排序数组

日常算法练习题寻找两个正序数组的中位数(每天进步一点点系列)

如何从一组数字计算平均值,中位数,模式和范围

如何在 C# 中计算“五的中位数”?