2010-08-21 6 views
26

Ho una matrice di elementi. Se faccio un arr.max otterrò il valore massimo. Ma mi piacerebbe avere l'indice dell'array. Come trovarlo in RubyCome trovare l'indice di un array che ha un valore massimo

Per esempio

a = [3,6,774,24,56,2,64,56,34] 
=> [3, 6, 774, 24, 56, 2, 64, 56, 34] 
>> a.max 
a.max 
=> 774 

ho bisogno di sapere l'indice di quella che è 7742. Come posso farlo in Ruby?

+0

Questa domanda equivale a parte della domanda posta a http://stackoverflow.com/questions/1656677/how-do-i-inde-a-geger-max-integer-in-an-array-for-ruby- e-return-the-indexed-p –

risposta

33
a.index(a.max) should give you want you want 
+9

Questo passerà attraverso la matrice due volte però. – sepp2k

+1

Almeno in Python, è più veloce attraversare l'array due volte nelle funzioni scritte in C piuttosto che essere più intelligente nel codice interpretato: http://lemire.me/blog/archives/2011/06/14/the- interpreti di lingua-sono-le-nuove-macchine/ – RecursivelyIronic

+0

sta iterando attraverso l'array con ciascuno e utilizzando un confronto per tenere traccia della corrente massima più veloce di questa soluzione? – srlrs20020

6

che dovrebbe funzionare

[7,5,10,9,6,8].each_with_index.max 
25

In 1.8.7+ each_with_index.max restituirà una matrice contenente l'elemento massimo e il suo indice:

[3,6,774,24,56,2,64,56,34].each_with_index.max #=> [774, 2] 

In 1.8.6 si può usare enum_for per ottenere lo stesso effetto:

require 'enumerator' 
[3,6,774,24,56,2,64,56,34].enum_for(:each_with_index).max #=> [774, 2] 
Problemi correlati