来自Ruby文档:
ary & other_ary→new_ary Set交集-返回一个新数组,其中包含两个数组共有的元素,不包括任何重复的元素。顺序从原始数组中保留下来。
但是,是否有一个内置的方法来执行(包括重复的)相同的事情?
测试用例:
ary = [2, 7, 3, 7]
other_ary = [7, 2, 7, 4]
new_ary == [2, 7, 7]发布于 2016-09-18 10:54:30
下面的解决方案并不是最优雅的解决方案,但它在任何情况下都会返回正确的答案:
[ary, other_ary].map { |e| e.group_by { |e| e } } # &:itself since 2.3
.reduce { |memo, h| memo.merge(h) do |k, o, n|
[o.count, n.count].min
end } # merge to count
.select { |_, v| Integer === v } # select only merged
.flat_map { |k, v| [k] * v } # produce a result或者,更优雅的变异数组:
a1, a2 = [ary, other_ary].map(&:dup) # to keep originals intact
loop.inject([]) do |memo|
break memo if a1.empty?
memo << (a2.delete_at(a2.index a1.pop) rescue nil)
end.compact
#⇒ [7, 7, 2]甚至:
a1, a2 = [ary, other_ary].map(&:dup) # to keep originals intact
loop.each_with_object([]) do |_, memo|
break memo if a1.empty?
a2.index(a1.pop).tap { |i| memo << a2.delete_at(i) if i }
end发布于 2016-09-18 08:53:29
也许是这样的?
ary.select{ |a| other_ary.include? a }
#=> [2, 7, 7]发布于 2016-09-19 18:18:13
我对这个问题的理解是,给您两个数组,a和b,并希望返回第三个数组,其中包含a和b中每个元素e的n副本,其中n = [a.count(e), a.count(e)].max。
假设
a = [3,1,2,1,0,1]
b = [1,2,4,2,4,6]我建议你执行以下三个步骤。
为每个数组构造一个计数散列
ha = a.each_with_object(Hash.new(0)) { |n,h| h[n] += 1 }
#=> {3=>1, 1=>3, 2=>1, 0=>1}
hb = b.each_with_object(Hash.new(0)) { |n,h| h[n] += 1 }
#=> {1=>1, 2=>2, 4=>2, 6=>1} 确定两个数组的公共元素
common_elements = a & b
#=> [1, 2]构造所需的数组
common_elements.flat_map { |n| [n]*[ha[n], hb[n]].max }
#=> [1, 1, 1, 2, 2] https://stackoverflow.com/questions/39555742
复制相似问题