在一个数组中计算元素出现的次数

3
我有一个包含元素[50, 20, 20, 5, 2]的数组,称为coins_used
我需要计算并输出一个硬币在数组中出现的次数。使用硬币x频率格式输出。
有没有办法计算元素在数组中出现的次数,输出应该像这样:50x1,20x2,5x1,2x1
最简单的方法是什么?

1
你看过 Array 类中提供的各种方法了吗 - http://ruby-doc.org/core-2.2.0/Array.html?在发帖提问之前,你尝试过什么? - Wand Maker
4个回答

6
使用Array#uniq,可以获取数组中的唯一元素。而Array#count将返回数组中找到的项目数。
通过将映射数组与,连接起来,您可以获得所需内容:

加入

a = [50,20,20,5,2]
a.uniq.map { |x| "#{x}x#{a.count(x)}" }.join(',')
# => "50x1,20x2,5x1,2x1"

更新:更高效的版本使用Hash进行计数。

a = [50,20,20,5,2]
freq = Hash.new(0)
a.each { |x| freq[x] += 1 }
freq.map{ |key, value| "#{key}x#{value}" }.join(',')
# => "50x1,20x2,5x1,2x1"

@SergioTulentsev,啊..我更新了答案。谢谢你指出来。 - falsetru

3

使用 Ruby >= 2.7,您可以执行以下操作:

coins_used = [50, 20, 20, 5, 2]
tally = coins_used.tally
tally.map { |k,v| "#{k}x#{v}" }.join(',')
=> "50x1,20x2,5x1,2x1"

1

Ruby标准库真的应该包含这样一个方法(我在我的.pryrc中使用它,我每天都用它)

module Enumerable
  def count_by(&block)
    each_with_object(Hash.new(0)) do |elem, memo|
      value = block.call(elem)
      memo[value] += 1
    end
  end
end

你可以这样使用它:

[50, 20, 20, 5, 2].count_by{|e| e} # => {50=>1, 20=>2, 5=>1, 2=>1}
# ruby 2.2
[50, 20, 20, 5, 2].count_by(&:itself) # => {50=>1, 20=>2, 5=>1, 2=>1}

将这个哈希转换为所需格式的字符串是由您完成的 :)

1
你可以使用 group_byitself
a = [50,20,20,5,2]
a.group_by(&:itself).map { |k, v| "#{k}x#{v.size}" }.join(',')
# => "50x1,20x2,5x1,2x1"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接