运维开发网
广告位招商联系QQ:123077622
 
广告位招商联系QQ:123077622

Ruby中的MapReduce数组

运维开发网 https://www.qedev.com 2020-05-25 19:27 出处:网络 作者:运维开发网整理
我有两个像这样的数组: ["1","7","8","10"] 和 ["1","2","3","6","9","11"] 这些数组表示用户选择的名为Place的类中的ID.我想选择投票最多的地方ID.我尝试了转置,但由于阵列有不同的大小,它们无法转置. 此示例的预期输出为: { "1" => 2, "7" => 1, "8" => 1, "10" => 1, "2" => 1, "3" => 1,
我有两个像这样的数组:

["1","7","8","10"]

["1","2","3","6","9","11"]

这些数组表示用户选择的名为Place的类中的ID.我想选择投票最多的地方ID.我尝试了转置,但由于阵列有不同的大小,它们无法转置.

此示例的预期输出为:

{ "1" => 2, "7" => 1, "8" => 1, "10" => 1, "2" => 1, "3" => 1, "6" => 1, "9" => 1, "11" => 1 }
您可以连接所有数组并计算相同元素的数量,如下所示:

arrays = [["1","7","8","10"], ["1","2","3","6","9","11"]].reduce(:+)
arrays.inject(Hash.new(0)) { |memo, e| memo.update(e => memo[e] + 1) }
# "{ "1" => 2, "7" => 1, "8" => 1, "10" => 1, "2" => 1, "3" => 1, "6" => 1, "9" => 1, "11" => 1 }"

获得此中间结果后,使用max_by从散列中选择具有最大值的键:

arrays = [["1","7","8","10"], ["1","2","3","6","9","11"]].reduce(:+)
arrays.inject(Hash.new(0)) { |memo, e| memo.update(e => memo[e] + 1) }
      .max_by { |_, count| count }[0]
#=> "1"

扫码领视频副本.gif

0

精彩评论

暂无评论...
验证码 换一张
取 消