[算法]如何用ruby统计数组或哈希中不同元素的个数?
黄舟
黄舟 2017-04-21 11:17:01
0
2
773

例如有如下数据:

a,b,c,a,c,d

  • 得到不同数据的值:a,b,c,d
  • 得到各个元素出现的个数:a => 2,b => 1,c => 2,d => 1

※数据出现不固定,可能有e,f,g等。

查了ruby文档的array和hash,没想出怎么实现。

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(2)
巴扎黑

Get the values ​​of different data:

%w(a b c a c d).uniq

Get the number of occurrences of each element:

count_hash = {}
%w(a b c a c d).each do |item|
  key = item.to_sym
  if count = count_hash[key]
    count_hash[key] = count + 1
  else
    count_hash[key] = 1
  end
end
迷茫
str='a,b,c,a,c,d'

counter = Hash.new(0)

str.split(',').each { |val| counter[val]+=1 }

puts counter
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!