算上红宝石数组重复元素 [英] count duplicate elements in ruby array

查看:111
本文介绍了算上红宝石数组重复元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个排序的数组是这样的:

  ['FATAL<错误标题=请求超时。>,
FATAL<错误标题=请求超时。>,
FATAL<错误标题=有足够的系统内存来运行此查询。>']

我想获得这样的事情(不一定是一个哈希值):

  [{:错误=> FATAL<错误标题=请求超时。>',:数=> 2}
{:错误=> FATAL<错误标题=有足够的系统内存来运行此查询。>',:数=> 1}]


解决方案

以下code的打印的你问什么。我会让你决定如何实际使用来产生你所寻找的哈希值:

 #样品阵列
A = [AA,BB,抄送,BB,BB,CC]#使哈希值默认为0,这样+ =将正常工作
B = Hash.new(0)#迭代这个数组,计数重复的条目
a.each做| V |
  B〔V] + = 1
结束b.each做| K,V |
  把#[KP}#显示{V}次
结束

注意:我只注意到你说的阵列已经排序。以上code不需要排序。使用该属性可产生更快的code。

I have an sorted array like this:

['FATAL <error title="Request timed out.">',
'FATAL <error title="Request timed out.">',
'FATAL <error title="There is insufficient system memory to run this query.">']

I would like to get something like this (does not have to be a hash):

[{:error => 'FATAL <error title="Request timed out.">', :count => 2}
{:error => 'FATAL <error title="There is insufficient system memory to run this query.">', :count => 1}]

解决方案

The following code prints what you asked for. I'll let you decide on how to actually use to generate the hash you are looking for:

# sample array
a=["aa","bb","cc","bb","bb","cc"]

# make the hash default to 0 so that += will work correctly
b = Hash.new(0)

# iterate over the array, counting duplicate entries
a.each do |v|
  b[v] += 1
end

b.each do |k, v|
  puts "#{k} appears #{v} times"
end

Note: I just noticed you said the array is already sorted. The above code does not require sorting. Using that property may produce faster code.

这篇关于算上红宝石数组重复元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆