2010-01-27 78 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)是更好的選擇。

相關問題