Ruby: How to find the key of the largest value in a hash?

前端 未结 5 1083
孤街浪徒
孤街浪徒 2020-12-17 05:18

Hello I\'m trying to find the largest value in my hash. I made a search in google and I found this code:

def largest_hash_key(hash)
  key = hash.sort{|a,b|          


        
相关标签:
5条回答
  • 2020-12-17 05:55

    Sort the hash once instead of finding max. This way you can also get smallest etc.

    def reverse_sort_hash_value(hash)
       hash = hash.sort_by {|k,v| v}.reverse
    end
    
    h = reverse_sort_hash_value(h)
    

    Key of largest value

    max = *h[0][0]
    

    Get Key/Value of the smallest value

    puts *h[h.length-1]
    

    You can convert to hash using Hash[h.select { |k, v| v == max}] or using h.to_h

    0 讨论(0)
  • 2020-12-17 05:56

    You can modify your method's first statement to

    key = hash.sort{|a,b| a[1] <=> b[1]}.last[0]
    

    Hash.sort returns an array of key-value pairs. last gets you the key-value pair with the largest value. Its first element is the corresponding key.

    0 讨论(0)
  • 2020-12-17 06:00

    This is O(n):

    h = {"n" => 100, "m" => 100, "y" => 300, "d" => 200, "a" => 0}
    key_with_max_value = h.max_by { |k, v| v }[0] #=> "y"
    
    0 讨论(0)
  • 2020-12-17 06:05

    I think it is not a good idea to use something you find on google and tweak it until it somehow runs. If we develop software, we should do something that we understand.

    A Hash is optimized to lookup a value by key. It is not optimized to sort the values or find by properties of the values. So the data structure is not helpful for your problem. Other data structures like trees or even arrays may be better.

    But if you want to use a hash because of some other reasons, of course it is possible. Somehow you just need to loop over the whole hash.

    The algorithm is quite easy: loop over the whole hash and check if the value is bigger and the previous biggest value:

    max_value = 0  # or -Infinity if you have negative values
    key_for_max_value = nil
    
    hash.each_pair do | key, value |
      if value > max_value
        max_value = value
        key_for_max_value = key
      end
    end
    puts "The largest value is #{max_value} and it is has the key #{key_for_max_value}"
    

    Some of the other solutions use tricks like to sort the array, but this only hides the complexity.

    0 讨论(0)
  • 2020-12-17 06:13

    Here is another way of doing what you want. This will find all the keys with the maximum value:

    h = {"n" => 100, "m" => 100, "y" => 300, "d" => 200, "a" => 0, "z" => 300}          
    max = h.values.max
    output_hash = Hash[h.select { |k, v| v == max}]
    puts "key(s) for the largest value: #{output_hash.keys}"
    
    #=>key(s) for the largest value: ["y", "z"]
    
    0 讨论(0)
提交回复
热议问题