给定这个数组数组,我如何计算自身包含重复元素的数组的数量?
Given this array of arrays, how do I count the number of arrays that include a duplicate element within itself?
我有一个如下所示的数组:
[[["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
我如何有效地做到这一点?
这个怎么样?
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
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
我有一个如下所示的数组:
[[["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
我如何有效地做到这一点?
这个怎么样?
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
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