如何检查红宝石阵列是否包含几个值之一?
题
我有两个红宝石阵列,我需要看看它们是否有任何共同值。我可以在一个数组中循环浏览每个值,然后在另一个数组中包含吗?(),但我敢肯定有更好的方法。它是什么? (阵列都固定字符串。)
谢谢。
解决方案
设置相交 他们:
a1 & a2
这是一个例子:
> a1 = [ 'foo', 'bar' ]
> a2 = [ 'bar', 'baz' ]
> a1 & a2
=> ["bar"]
> !(a1 & a2).empty? # Returns true if there are any elements in common
=> true
其他提示
有什么共同价值吗?您可以使用十字路口操作员: &
[ 1, 1, 3, 5 ] & [ 1, 2, 3 ] #=> [ 1, 3 ]
但是,如果您正在寻找完整的交叉点(使用重复),则问题更为复杂,这里已经有一个堆栈溢出: 如何将红宝石阵列与重复元素返回? (骰子系数中的bigrams问题)
或快速 摘要 定义“ 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
使用相交看起来不错,但效率低下。我会用“任何?”在第一个数组(以便在第二个数组中找到其中一个元素时,迭代就会停止)。另外,使用第二阵列上的集合将使会员资格检查快速。 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
尝试这个
a1 = [ 'foo', 'bar' ]
a2 = [ 'bar', 'baz' ]
a1-a2 != a1
true
不隶属于 StackOverflow