2010-01-27 31 views
43

如果a是数组,我想要a.index(a.max),但更像Ruby。这应该是显而易见的,但我无法在其他地方找到答案。显然,我是Ruby的新手。在Ruby中,获取数组中最大值索引的最简洁方法是什么?

+2

我想你已经明白了。什么是非rubylike? – Ben 2010-01-27 19:52:27

+0

本,我正在寻找像a.max_index。猜测它不是内置的。 – 2010-01-29 18:28:51

+1

即使你想要的函数没有内置,你仍然可以在'Array'类中添加一个'.max_index'成员。以下是使用自定义成员来扩展'String'或'Integer'的示例:http://www.hawkee.com/snippet/1260/ – bta 2010-01-29 22:58:48

回答

99

对于红宝石1.8.7或以上:

a.each_with_index.max[1] 

它确实一次迭代。不完全是有史以来最有语义的事情,但是如果你发现自己做了这么多事情,无论如何我都会把它包装在一个index_of_max方法中。

+0

哇。这是怎么做到的? – 2010-01-27 20:14:30

+2

同意 - 这个工作怎么样? – bergyman 2010-01-27 20:15:46

+0

啊,知道了。 each_with_index.max返回一个数组,其中第一个元素是值,第二个元素是它的索引。很好,查克。 – bergyman 2010-01-27 20:24:53

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

至少它红宝石般:)

+0

该死的!我正在用注射剂制作一个解决方案 - 你击败了我! ;) – bergyman 2010-01-27 20:08:16

+2

另外 - 原来的问题是获得索引,所以这将不得不被改为: a.inject(0){| index,num | num> a [index]? a.find_index(num):index} – bergyman 2010-01-27 20:11:21

14

在红宝石1.9.2我可以做到这一点;

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

这基本上是不需要的原始解决方案的更糟糕的版本。 – MegaTom 2017-05-17 18:26:45

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 
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] 
1

只是想记下一些行为和性能差异这里的解决方案。在“平局决胜”的行为重复最大要素:

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) 

于是我产生了新的aArray.new(10_000_000) { Random.rand } and reran the test:

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)是更好的选择。

相关问题