【问题标题】:How to find the max value in an array of hashes?如何在哈希数组中找到最大值?
【发布时间】:2018-04-07 00:50:18
【问题描述】:

在这里给出这个哈希数组:

arr = [{:question_type=>"Fire", :total=>0.0}, {:question_type=>"Water", :total=>0.0}, {:question_type=>"Metal", :total=>0.0}, {:question_type=>"Earth", :total=>0.0}, {:question_type=>"Wood", :total=>100.0}]

我想为总键选择具有最高值的散列。 所以下面的代码似乎可以完成工作

max = arr.max_by{|x| x[:total]}
puts max[:question_type]
#=> Wood

但是,如果我有 2 个具有相同值的哈希,它将只返回第一个

arr2 = [{:question_type=>"Fire", :total=>0.0}, {:question_type=>"Water", :total=>0.0}, {:question_type=>"Metal", :total=>0.0}, {:question_type=>"Earth", :total=>50.0}, {:question_type=>"Wood", :total=>50.0}]

max = arr2.max_by{|x| x[:total]} #it should be arr2
puts max[:question_type]
#=> Earth

如果两者都是最大值,那么让它返回 EarthWood 的最佳方法是什么?

【问题讨论】:

标签: ruby-on-rails arrays ruby


【解决方案1】:

您可以使用group_bymax 做到这一点:

arr.group_by { |x| x[:total] }.max.last

【讨论】:

    【解决方案2】:

    您可以这样分两步完成:

    max = arr.max_by{|x| x[:total]}
    max = arr.select{ |x| x[:total] == max[:total }
    

    【讨论】:

      【解决方案3】:

      你总是可以只取最大值和select

      arr = [{:question_type=>"Fire", :total=>0.0}, {:question_type=>"Water", :total=>0.0}, {:question_type=>"Metal", :total=>0.0}, {:question_type=>"Earth", :total=>50.0}, {:question_type=>"Wood", :total=>50.0}]
      
      max = arr.max_by{|x| x[:total]}
      max_values = arr.select{|hash| hash[:total] == max[:total]}
      

      【讨论】:

        【解决方案4】:

        这里已经发布的一些可靠答案的另一种方法是滚动你自己的方法来检索最大值,如果有平局,包括倍数:

        def get_max(arr)
          result = []
          current_max = 0.0
          arr.each do |hash|
            if hash[:total] > current_max
              result = [hash[:question_type]]
              current_max = hash[:total]
            elsif hash[:total] == current_max
              result.push(hash[:question_type])
            end
          end
          result
        end
        
        
        arr = [{:question_type=>"Fire", :total=>0.0}, {:question_type=>"Water", :total=>0.0}, {:question_type=>"Metal", :total=>0.0}, {:question_type=>"Earth", :total=>50.0}, {:question_type=>"Wood", :total=>50.0}]
        puts get_max(arr)
        # => ["Earth", "Wood"]
        

        它可能不如使用#max_by#select 之类的东西简洁,但上述方法的好处是您只需遍历数组一次。

        希望对你有帮助!

        【讨论】:

        • 您可以使用each_with_object 重构此代码,或者改用reduce
        猜你喜欢
        • 2018-03-14
        • 2011-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-20
        • 2012-10-11
        • 2014-03-07
        • 1970-01-01
        相关资源
        最近更新 更多