Is there a method in Ruby that takes an array, and counts all unique elements and their occurrences and passes them back as a hash?

For example

  ['A','A','A','A','B','B','C'].method
> {'A' => 4, 'B' => 2, 'C' => 1}

Something like that.

['A','A','A','A','B','B','C'].group_by{|e| e}.map{|k, v| [k, v.length]}.to_h

src = ['A','A','A','A','B','B','C']
Hash[src.group_by { |x| x }.map { |k, v| [k, v.length] }]
counts = Hash.new(0)
['A','A','A','A','B','B','C'].each { |name| counts[name] += 1 }
counts => {"A"=>4, "B"=>2, "C"=>1}

['A','A','A','A','B','B','C'].each_with_object(Hash.new(0)) { |l, o| o[l] += 1 }

This is the easiest readable for me:

src = ['A','A','A','A','B','B','C']
src.group_by(&:to_s).to_a.map { |a| [a[0], a[1].count] }.to_h

Or here is another solution with reduce method:

src.reduce({}) { |b, a| b.merge({a => (b[a] || 0) + 1}) }

Or:

src.reduce(Hash.new(0)) { |b, a| b.merge({a => b[a] + 1}) }

Ruby: Count unique elements and their occurences in an array的更多相关文章

  1. [geeksforgeeks] Count the number of occurrences in a sorted array

    Count the number of occurrences in a sorted array Given a sorted array arr[] and a number x, write a ...

  2. FB面经 Prepare: Count Unique Island

    数unique island, 比如 110000 110001 001101 101100 100000 总共两个unique岛,不是四个 方法可以是记录每次新的岛屿搜索的路径,left,right ...

  3. leetcode 283 Move Zeros; 27 Remove Elements; 26 Remove Duplicated from Sorted Array;

    ,,,,}; //把数组的值赋给vector vector<int> vec(arr, arr+sizeof(arr)/sizeof(int)); 解法一: 时间复杂度O(n) 空间复杂度 ...

  4. [Algorithm] Count occurrences of a number in a sorted array with duplicates using Binary Search

    Let's say we are going to find out number of occurrences of a number in a sorted array using binary ...

  5. numpy.unique

    Find the unique elements of an array. Returns the sorted unique elements of an array. There are thre ...

  6. [Swift]LeetCode347. 前K个高频元素 | Top K Frequent Elements

    Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nums = [ ...

  7. Leetcode 347. Top K Frequent Elements

    Given a non-empty array of integers, return the k most frequent elements. For example,Given [1,1,1,2 ...

  8. 【ruby】ruby基础知识

    Install Ruby(安装) For windows you can download Ruby from http://rubyforge.org/frs/?group_id=167 for L ...

  9. Non-unique Elements

    Non-unique Elements You are given a non-empty list of integers (X). For this task, you should return ...

随机推荐

  1. HTML5_文本元素

    <!DOCTYPE html> <hmtl> <html  lang="zh-en"> <head> <meta  chars ...

  2. Directx11学习笔记【十九】 摄像机的实现

    本文由zhangbaochong原创,转载请注明出处:http://www.cnblogs.com/zhangbaochong/p/5785100.html 之前为了方便观察场景,我们采用的方法是鼠标 ...

  3. VS2013验证控件出现 WebForms UnobtrusiveValidationMode 必须“jquery”ScriptResour......错误的解决方案

    如下面的错误: 解决方式例如以下: 方法一: 在webconfig中找到 <appSettings> <addkey="aspnet:UseTaskFriendlySync ...

  4. zoj3829 Known Notation --- 2014 ACM-ICPC Asia Mudanjiang Regional Contest

    根据规则,可以发现,一*之前必须有至少2数字.一(11*)这反过来可以被视为一数字. 因此,总位数必须大于*号码,或者你会加入数字. 添加数字后,,为了确保该解决方案将能够获得通过交流.那么肯定是*放 ...

  5. MySQL InnoDB存储引擎undo redo解析

    本文介绍MySQL数据库InnoDB存储引擎重做日志漫游 00 – Undo Log Undo Log 为了实现事务原子,在MySQL数据库InnoDB存储引擎,还使用Undo Log(简称:MVCC ...

  6. T-SQL中default值的使用

    今天介绍一下通过T-SQL语句来创建表时使用default的关键字来自动使用默认值,这个关键字和其它的如:identity,primary key ,not null ,unique等不是相同,这里简 ...

  7. 阿里巴巴2014年校园招聘(秋季招聘)在线笔试--測试研发project师

    第一部分是单选题:40分钟答题时间. watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveG1oMTk1NA==/font/5a6L5L2T/fontsize/ ...

  8. Ural 1309 Dispute (递归)

    意甲冠军: 给你一个数列: f(0) = 0 f(n) = g(n,f(n-1)) g(x,y) = ((y-1)*x^5+x^3-xy+3x+7y)%9973 让你求f(n)  n <= 1e ...

  9. ISAPI_Rewrite 3 伪静态软件

    下载地址 http://www.helicontech.com/isapi_rewrite/download.html

  10. SQL Server 开发利器 SQL Prompt 6.5 T-SQL智能感知分析器 下载地址 完全破解+使用教程

    SQL脚本越写越多,总是觉得编写效率太过于低下,这和打字速度无关.在我个人编写SQL脚本时,至少会把SQL的格式排列成易于阅读的,因为其他人会阅读到你的SQL,无论是在程序中或是脚本文件中,良好的排版 ...