【问题标题】:How to find the index of an array which has a maximum value如何找到具有最大值的数组的索引
【发布时间】:2010-08-21 19:40:32
【问题描述】:

我有一个元素数组。如果我执行arr.max,我将获得最大值。但我想获取数组的索引。如何在 Ruby 中找到它

例如

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

我需要知道774 的索引,即2。我如何在 Ruby 中做到这一点?

【问题讨论】:

标签: ruby arrays


【解决方案1】:
a.index(a.max)  should give you want you want

【讨论】:

  • 这将通过数组两次。
  • 至少在 Python 中,在用 C 编写的函数中遍历数组两次要比在解释代码中更聪明:lemire.me/blog/archives/2011/06/14/…
  • 是否正在遍历数组,并使用比较来比此解决方案更快地跟踪当前最大值?
【解决方案2】:

在 1.8.7+ 中,each_with_index.max 将返回一个包含最大元素及其索引的数组:

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

在 1.8.6 中你可以使用enum_for 来获得同样的效果:

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

【讨论】:

    【解决方案3】:

    应该可以的

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

    【讨论】:

      猜你喜欢
      • 2018-04-25
      • 2016-08-21
      • 2014-05-19
      • 1970-01-01
      • 2011-11-12
      • 2019-08-21
      • 2019-08-27
      • 2018-05-05
      相关资源
      最近更新 更多