代码之家  ›  专栏  ›  技术社区  ›  Cary Swoveland

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

  •  48
  • Cary Swoveland  · 技术社区  · 16 年前

    如果 a 是阵列,我要 a.index(a.max) 但更像红宝石。这应该很明显,但我在某地和其他地方很难找到答案。显然,我对鲁比还不熟悉。

    6 回复  |  直到 8 年前
        1
  •  103
  •   Chuck    16 年前

    对于Ruby 1.8.7或更高版本:

    a.each_with_index.max[1]
    

    它执行一次迭代。不是最语义化的东西,但是如果你发现自己经常这样做,我会用一个 index_of_max 无论如何方法。

        2
  •  14
  •   eastafri    14 年前

    在Ruby1.9.2中,我可以做到这一点;

    arr = [4, 23, 56, 7]
    arr.rindex(arr.max)  #=> 2
    
        3
  •  6
  •   Arup Rakshit    10 年前

    我想回答这个问题:

    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
    
        4
  •  3
  •   Alex Moore-Niemi    8 年前

    只是想注意一些解决方案的行为和性能差异。“断线”行为 复制品 最大元素:

    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)
    

    然后我生成了一个新的 具有 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) 是更好的选择。

        5
  •  2
  •   Jarrett Meyer    16 年前
    a = [1, 4 8]
    a.inject(a[0]) {|max, item| item > max ? item : max }
    

    至少是红宝石般的:)

        6
  •  1
  •   dawg    8 年前

    这里有一种方法可以获取最大值(如果不止一个)的所有索引值。

    鉴于:

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