Find most common string in an array

前端 未结 6 1892
说谎
说谎 2020-12-24 07:42

I have this array, for example (the size is variable):

   x = [\"1.111\", \"1.122\", \"1.250\", \"1.111\"]

and I need to find the most comm

6条回答
  •  遥遥无期
    2020-12-24 08:20

    Using the default value feature of hashes:

    >> x = ["1.111", "1.122", "1.250", "1.111"]
    >> h = Hash.new(0)
    >> x.each{|i| h[i] += 1 }
    >> h.max{|a,b| a[1] <=> b[1] }
    ["1.111", 2]
    

提交回复
热议问题