红宝石:如何找到阵列项目中最有发生? [英] Ruby: How to find item in array which has the most occurrences?
本文介绍了红宝石:如何找到阵列项目中最有发生?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
[1,1,1,2,3] .mode
= GT; 1['猫','狗','蛇','狗'。模式
= GT;狗
解决方案
先建立一个哈希数组中的每个值映射到其频率...
改编= [1,1,1,2,3]频率= arr.inject(Hash.new(0)){| H,V | H [V] + = 1; H }
#=> {1 =→3,2 =大于1,3 =大于1}
...然后使用频率表以找到具有最高频率的元素:
arr.max_by {| V | FREQ [V]}
#=> 1
[1, 1, 1, 2, 3].mode
=> 1
['cat', 'dog', 'snake', 'dog'].mode
=> dog
解决方案
First build a hash mapping each value in the array to its frequency…
arr = [1, 1, 1, 2, 3]
freq = arr.inject(Hash.new(0)) { |h,v| h[v] += 1; h }
#=> {1=>3, 2=>1, 3=>1}
… then use the frequency table to find the element with the highest frequency:
arr.max_by { |v| freq[v] }
#=> 1
这篇关于红宝石:如何找到阵列项目中最有发生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文