ruby - 为什么 [20, ..., 13, 14].min(2) => [13, 20]?

标签 ruby min

[20, 32, 32, 21, 30, 25, 29, 13, 14].min(2)
# => [13, 20]

为什么不是 [13, 14] ?我如何得到我想要的两个最小元素(线性时间)?

The doc的句子 “如果给出了 n 个参数,则最小 n 个元素作为数组返回” 对我来说不是很清楚,但我认为它说的是 min(2)应该给我最小的两个元素。我找不到太多关于它的信息,但是this thread ,这可能是起源,似乎同意我的看法,并说它应该返回与 sort.first(n) 相同的结果。 ,它没有:

[20, 32, 32, 21, 30, 25, 29, 13, 14].sort.first(2)
# => [13, 14]

很抱歉,这个愚蠢的问题和“大”示例很抱歉,但这已经减少了 - 再删除一个数字(13 或 14 除外)确实会给我 [13, 14] .

最佳答案

我刚刚在 Ruby Issue Tracking System 中发布了对错误的解释:

I suppose I found the problem. Taking the first example:

[20, 32, 32, 21, 30, 25, 29, 13, 14].min(2)

This will call the function "nmin_run" in the file "enum.c", which sets "bufmax" to 4 times the number of minimums (n) we want (for the example, bufmax is 8), and then in the line 1327 will call the function "nmin_i" for each element of the original array.

In the function "nmin_i", when the buffer is full ("data->curlen == data->bufmax"), the function "nmin_filter" is called. In the example, that happens when curlen is 8, and so the buffer is [20, 32, 32, 21, 30, 25, 29, 13]. The "nmin_filter" will do a quicksort until the n smallest elements so far are on the leftmost part of the buffer, and will discard the rest of the elements, which leaves us with [20, 13] in the buffer.

And now starts the problem. At the end of "nmin_filter" the limit (apparently with the intention of storing the greatest value in the buffer) is set to the last value in the buffer (in the example, 13), which is not true. And then based on that value "nmin_i" will discard all remaining elements greater than that (in the example, discarding the 14). The buffer is then sorted and it returns:

[13, 20]

So the solution is either remove all the limit-related part, or take the last pivot as the limit.

关于ruby - 为什么 [20, ..., 13, 14].min(2) => [13, 20]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32121749/

相关文章:

Python:获取元组列表中的最小整数

c# - 如何获取数组中每个元素的绝对值

python - 如何将 Faktory 与 ruby​​ 作业和 python 作业一起使用?

ruby - 与另一个项目并行开发 gem

ruby - Buildr——调试构建文件

ruby - 我是否因为没有为 gems 安装 ri 和 rdoc 而遗漏了什么?

java - 从 JAVA(MYSQL Insert 语句)和 delayed_jobs ruby​​ gem 处理的队列中手动输入延迟作业表

C 扩展 : <? 和 >?运营商

SQL Server 查询根据传递关系查找最小日期

c++ - Max 和 Min 显示为 true 而不是数字,我该怎么办?