Project

General

Profile

Feature #11315 » array_xor.patch

0x0dea (D.E. Akers), 06/28/2015 02:22 PM

View differences:

array.c
return ary3;
}
/*
* call-seq:
* ary ^ other_ary -> new_ary
*
* Symmetric Difference --- Returns a new array containing the elements
* which appear in either +ary+ or +other_ary+, but not both. The order
* is preserved from the original array.
*
* It compares elements using their #hash and #eql? methods for efficiency.
*
* [1, 2, 3] ^ [2, 3, 4] # => [1, 4]
*
* If you need set-like behavior, see the library class Set.
*/
static VALUE
rb_ary_xor(VALUE ary1, VALUE ary2)
{
VALUE hash, ary3;
st_data_t elt;
long i;
ary2 = to_ary(ary2);
hash = ary_make_hash(ary1);
for (i = 0; i < RARRAY_LEN(ary2); ++i) {
elt = (st_data_t)RARRAY_AREF(ary2, i);
if (st_lookup(RHASH_TBL_RAW(hash), elt, 0)) {
st_delete(RHASH_TBL_RAW(hash), &elt, 0);
}
else {
st_update(RHASH_TBL_RAW(hash), elt, ary_hash_orset, elt);
}
}
ary3 = rb_hash_values(hash);
ary_recycle_hash(hash);
return ary3;
}
static int
push_value(st_data_t key, st_data_t val, st_data_t ary)
{
......
rb_define_method(rb_cArray, "-", rb_ary_diff, 1);
rb_define_method(rb_cArray, "&", rb_ary_and, 1);
rb_define_method(rb_cArray, "|", rb_ary_or, 1);
rb_define_method(rb_cArray, "^", rb_ary_xor, 1);
rb_define_method(rb_cArray, "uniq", rb_ary_uniq, 0);
rb_define_method(rb_cArray, "uniq!", rb_ary_uniq_bang, 0);
test/ruby/test_array.rb
assert_equal([obj1], [obj1]|[obj2])
end
def test_XOR
assert_equal(@cls[], @cls[] ^ @cls[])
assert_equal(@cls[1], @cls[1] ^ @cls[])
assert_equal(@cls[1], @cls[] ^ @cls[1])
assert_equal(@cls[], @cls[1] ^ @cls[1])
assert_equal(@cls[1,2], @cls[1] ^ @cls[2])
assert_equal(@cls[1,4], @cls[1,2,3] ^ @cls[2,3,4])
end
def test_combination
assert_equal(@cls[[]], @cls[1,2,3,4].combination(0).to_a)
assert_equal(@cls[[1],[2],[3],[4]], @cls[1,2,3,4].combination(1).to_a)
(1-1/3)