What is an efficient way to find disjoint elements in two arrays?

I have the following arrays:

A = [1,2,3,4,5] B = [2,6,7,1] 

I want to find disjoint elements that look like this:

 output = [3,4,5,6,7] 

I was able to achieve this as follows:

 output = A + B - (A & B) 

but it is inefficient as I add two arrays and then delete the common elements. This is similar to finding disjoint elements. Can I do it better than this? If so, how?

+5
source share
3 answers

How to simply select elements in A, not in B, and elements from B not in A.

 (A - B) + (B - A) 
+6
source

You can use set

 A = Set[1,2,3,4,5] => #<Set: {5, 1, 2, 3, 4}> B = Set[2,6,7,1] => #<Set: {6, 1, 7, 2}> C = A ^ B => #<Set: {5, 6, 7, 3, 4}> C.to_a => [5, 6, 7, 3, 4] 
+6
source

Other:

 (A | B) - (A & B) 

But you probably want to use your own version:

 require 'benchmark' n = 50000 A = (1..1000).to_a B = [2,6,7,1] Benchmark.bm do |x| x.report { n.times do; (A + B) - (A & B); end } x.report { n.times do; (A - B) + (B - A); end } x.report { n.times do; (A | B) - (A & B); end } x.report { n.times do; (Set[*A] ^ Set[*B]).to_a; end } end user system total real 2.200000 0.000000 2.200000 ( 2.208357) 9.600000 0.010000 9.610000 ( 9.591845) 10.630000 0.000000 10.630000 ( 10.621927) 31.420000 0.000000 31.420000 ( 31.418155) 
+5
source

Source: https://habr.com/ru/post/1243384/


All Articles