在Ruby中,获取数组中最大值索引的最简洁方法是什么?

时间:2010-01-27 19:47:24

标签: ruby arrays indexing max

如果a是数组,我想要a.index(a.max),但更像Ruby。这应该是显而易见的,但我无法在其他地方找到答案。显然,我是Ruby的新手。

6 个答案:

答案 0 :(得分:106)

对于Ruby 1.8.7或更高版本:

a.each_with_index.max[1]

它进行一次迭代。不完全是最具语义性的东西,但是如果你发现自己做了很多这样的话,我会用index_of_max方法将它包装起来。

答案 1 :(得分:14)

在ruby 1.9.2中,我可以这样做;

arr = [4, 23, 56, 7]
arr.rindex(arr.max)  #=> 2

答案 2 :(得分:6)

我正在考虑回答这个问题:

a = (1..12).to_a.shuffle
# => [8, 11, 9, 4, 10, 7, 3, 6, 5, 12, 1, 2]
a.each_index.max_by { |i| a[i] }
# => 9

答案 3 :(得分:3)

只是想在这里注意一些解决方案的行为和性能差异。 重复最大元素的“打破平局”行为:

a = [3,1,2,3]
a.each_with_index.max[1]
# => 3
a.index(a.max)
# => 0

出于好奇,我在Benchmark.bm(上面的a)中运行了它们:

user     system      total        real
each_with_index.max  0.000000   0.000000   0.000000 (  0.000011)
index.max  0.000000   0.000000   0.000000 (  0.000003)

然后我使用a生成了一个新的Array.new(10_000_000) { Random.rand }并重新进行了测试:

user     system      total        real
each_with_index.max
  2.790000   0.000000   2.790000 (  2.792399)
index.max  0.470000   0.000000   0.470000 (  0.467348)

这让我觉得除非你特别需要选择更高的索引最大值,a.index(a.max)是更好的选择。

答案 4 :(得分:2)

a = [1, 4 8]
a.inject(a[0]) {|max, item| item > max ? item : max }

至少它是类似Ruby的:)

答案 5 :(得分:1)

这是一种获取最大值的所有索引值的方法,如果不止一个。

假设:

> a
=> [1, 2, 3, 4, 5, 6, 7, 9, 9, 2, 3]

您可以通过以下方式找到所有最大值(或任何给定值)的索引:

> a.each_with_index.select {|e, i| e==a.max}.map &:last
=> [7, 8]
相关问题