【问题标题】:Given this array of arrays, how do I count the number of arrays that include a duplicate element within itself?给定这个数组数组,我如何计算其中包含重复元素的数组的数量?
【发布时间】:2020-01-20 03:08:09
【问题描述】:

我有一个如下所示的数组:

[[["Sports", "Soccer"], 2], [["eSports"], 1], [["Sports", "Soccer"], 3]]

在最外层数组的任何元素中,第一个元素(数组)是类别列表。第二个元素是 program.id 这个类别数组来自。

因此,取上述数组中的第一个元素 - ["Sports", "Soccer"]program_id: 2 的类别数组。

如何计算类别数组重复的实例?在上述情况下,我想要的是这样的:

["Sports", "Soccer"] => Occurs 2 times, with Program Ids: 2 & 3
["eSports"] => Occurs 1 time, with Program Id: 1

我如何有效地做到这一点?

【问题讨论】:

  • 内部数组中元素的顺序是否重要。例如,[[["Sports", "Soccer"], 2], [["Soccer", "Sports"], 3]] 的期望返回值是多少?

标签: arrays ruby-on-rails ruby ruby-on-rails-6


【解决方案1】:
grouped = array.group_by { |s, id| s }.transform_values { |v| v.map(&:last) }

=> { ["Sports", "Soccer"] => [2, 3], 
     ["eSports"]          => [1] }

使用它:

grouped.each { |k,v| 
  puts "[#{k.join(', ')}] occurs #{v.length} time(s) with ID: #{v.join(' and ')}" 
}

[Sports, Soccer] occurs 2 time(s) with ID: 2 and 3
[eSports] occurs 1 time(s) with ID: 1

【讨论】:

  • 我喜欢这个,但它没有告诉我每个实例有多少个存在。它只是重新格式化它并从 ID 中分解类别。
  • 嗯。你什么意思?它通过结果数组的长度告诉您实例的数量。示例[2,3],表示两个实例,一个 ID 为 2,另一个 ID 为 3。
【解决方案2】:

这个怎么样?

arr = [[["Sports", "Soccer"], 2], [["eSports"], 1], [["Sports", "Soccer"], 3]]
count = {}
arr.each do |el|
  count[el[0]] ||= []
  count[el[0]] << el[1]
end

count.each do |category, ids|
  puts "#{category} occurs #{ids.count} times, with Program Ids: #{ids.join(' & ')}"
end

输出

["Sports", "Soccer"] occurs 2 times, with Program Ids: 2 & 3
["eSports"] occurs 1 times, with Program Ids: 1

【讨论】:

  • Hrmm...请记住,我想计算完整的第一个元素,而不是第一个元素中的第一个元素。即["Sports", "Soccer"],而不是["Sports"]["Soccer"]。它必须是包含两个元素的完整数组。这就是我要计算的实例。这已经发生了两次。
  • 我编辑了答案。但我注意到@casper 的答案更简单。
  • 您可以简化为arr.each_with_object({}) { |el,count| (count[el.first] ||= []) &lt;&lt; el.last }arr.each_with_object(Hash.new { |h,k| h[k] = [] }) { |el,count| count[el.first] &lt;&lt; el.last }
猜你喜欢
  • 2020-02-03
  • 2020-12-01
  • 1970-01-01
  • 2012-02-21
  • 1970-01-01
  • 1970-01-01
  • 2019-11-06
  • 1970-01-01
相关资源
最近更新 更多