2017-09-23 135 views

回答

3
def appears_in_all(arr) 
    arr.reduce(:&) 
end 

appears_in_all [[573, 574], [573, 574], [573], [573, 574]]   #=> [573] 
appears_in_all [[573, 574], [573, 574], [573, 574, 578], [573, 574]] #=> [573, 574] 
appears_in_all [[573, 574], [573, 574], [573], [573, 574], [2, 4]] #=> [] 
+0

感谢它的作品 – AdamM

1
items.flatten.uniq.select{|x| items.map{|y| y.include? x}.all?} 
3

您可以在items最小的子阵列(将搜索限制设置),然后选择所有从阵列中items出现在所有其他数组中的元素:

items.min_by(&:length).select do |element| 
    items.all? { |sub_array| sub_array.include?(element) } 
end 
# => [573] 

如果它保证只有一个元素是所有的人,你可以使用detect代替select

+0

我必须使用评论说是一个非常干净的搜索解决方案ñ。 –

相关问题