Mar*_*ers 84
设置相交:
a1 & a2
Run Code Online (Sandbox Code Playgroud)
这是一个例子:
> a1 = [ 'foo', 'bar' ]
> a2 = [ 'bar', 'baz' ]
> a1 & a2
=> ["bar"]
> !(a1 & a2).empty? # Returns true if there are any elements in common
=> true
Run Code Online (Sandbox Code Playgroud)
有什么共同的价值?你可以使用交叉算子:&
[ 1, 1, 3, 5 ] & [ 1, 2, 3 ] #=> [ 1, 3 ]
Run Code Online (Sandbox Code Playgroud)
如果你正在寻找一个完整的交叉点(有重复),问题就更复杂了,这里已经有一个堆栈溢出:如何返回一个带有重复元素的Ruby数组交集?(骰子系数中的双字母问题)
或者是一个快速片段,它定义"real_intersection"并验证以下测试
class ArrayIntersectionTests < Test::Unit::TestCase
def test_real_array_intersection
assert_equal [2], [2, 2, 2, 3, 7, 13, 49] & [2, 2, 2, 5, 11, 107]
assert_equal [2, 2, 2], [2, 2, 2, 3, 7, 13, 49].real_intersection([2, 2, 2, 5, 11, 107])
assert_equal ['a', 'c'], ['a', 'b', 'a', 'c'] & ['a', 'c', 'a', 'd']
assert_equal ['a', 'a', 'c'], ['a', 'b', 'a', 'c'].real_intersection(['a', 'c', 'a', 'd'])
end
end
Run Code Online (Sandbox Code Playgroud)
使用交集看起来不错,但效率低下。我会用“任何?” 在第一个数组上(以便在第二个数组中找到一个元素时停止迭代)。此外,在第二个数组上使用 Set 将使成员资格检查快速。IE:
a = [:a, :b, :c, :d]
b = Set.new([:c, :d, :e, :f])
c = [:a, :b, :g, :h]
# Do a and b have at least a common value?
a.any? {|item| b.include? item}
# true
# Do c and b have at least a common value?
c.any? {|item| b.include? item}
#false
Run Code Online (Sandbox Code Playgroud)