计算数组中的中位数-有人可以告诉我这段代码中的情况吗? [英] Calculate Median in An Array - Can someone tell me what is going on in this line of code?

查看:108
本文介绍了计算数组中的中位数-有人可以告诉我这段代码中的情况吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是用于计算数组中位数的解决方案.我得到前三行,duh;),但是第三行是发生魔术的地方.有人可以解释"sorted"变量的用法,为什么将其放在方括号旁边,为什么将另一个变量"len"括在括号中,然后放在方括号中吗?几乎就像排序后突然被用作数组一样吗?谢谢!

This is a solution for calculating the median value in an array. I get the first three lines, duh ;), but the third line is where the magic is happening. Can someone explain how the 'sorted' variable is using and why it's next to brackets, and why the other variable 'len' is enclosed in those parentheses and then brackets? It's almost like sorted is all of a sudden being used as an array? Thanks!

  def median(array)
    sorted = array.sort
    len = sorted.length
    return ((sorted[(len - 1) / 2] + sorted[len / 2]) / 2.0).to_f
  end

  puts median([3,2,3,8,91])
  puts median([2,8,3,11,-5])
  puts median([4,3,8,11])

推荐答案

是的,array.sort返回一个数组,并将其分配给sorted.然后,您可以通过数组索引访问它.

Yes, array.sort is returning an array and it is assigned to sorted. You can then access it via array indices.

如果元素的数量为奇数,例如在示例中说5个元素,则索引为:

If you have an odd number of elements, say 5 elements as in the example, the indices come out to be:

(len-1)/2=(5-1)/2=2

len/2=5/2=2 --- (remember this is integer division, so the decimal gets truncated)

因此,您将索引2的值加起来,然后除以2,这与索引2的值相同.

So you take the value at index 2 and add them, and then divide by 2, which is the same as the value at index 2.

如果元素的数量为偶数,则说4,

If you have an even number of elements, say 4,

(len-1)/2=(4-1)/2=1 --- (remember this is integer division, so the decimal gets truncated)

len/2=4/2=2

因此,在这种情况下,您可以有效地平均两个中间元素1和2,这是当元素个数为偶数时中位数的定义.

So in this case, you are effectively averaging the two middle elements 1 and 2, which is the definition of median for when you have an even number of elements.

这篇关于计算数组中的中位数-有人可以告诉我这段代码中的情况吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆