ruby: how to find non-unique elements in array and print each with number of occurrences?

后端 未结 8 1610
轻奢々
轻奢々 2020-12-31 03:54

I have

a = [\"a\", \"d\", \"c\", \"b\", \"b\", \"c\", \"c\"]

and need to print something like (sorted descending by number of occurrences)

8条回答
  •  猫巷女王i
    2020-12-31 04:02

    a.reduce(Hash.new(0)) { |memo,x| memo[x] += 1; memo } # Frequency count.
      .select { |_,count| count > 1 } # Choose non-unique items.
      .sort_by { |x| -x[1] } # Sort by number of occurrences descending.
    # => [["c", 3], ["b", 2]]
    

    Also:

    a.group_by{|x|x}.map{|k,v|[k,v.size]}.select{|x|x[1]>1}.sort_by{|x|-x[1]}
    # => [["c", 3], ["b", 2]]
    

提交回复
热议问题