Finding the symmetric difference of two arrays

January 26, 2019
I try to bend the internet to my will.
Wizard 26 posts
Followers: 19 people
0

Finding the symmetric difference of two arrays

I try to bend the internet to my will.
Wizard 26 posts
Followers: 19 people
January 26, 2019

My previous two posts looked at intersection of arrays and Union and diff of arrays. This time I’m going to look at finding the symmetric difference.

So first, what the heck is a symmetric difference? It’s sometimes called a disjunctive union A △ B and is the name given for finding the values in each set that do not exist in the other set. For example, the symmetric difference of [1,2,3] and [3,4] is [1,2,4].

To do this, we need to find the intersection and then remove the intersection values from the union of the two arrays. Using the union function from the Union and diff of arrays blog post combined with the intersection function from the intersection-of-arrays blog post we end up with:

function intersection(a, b) {
    var result = a.clone();
    result.retainAll(b);
    return result;
}
function union(a, b) {
    var result = a.clone();
    result.removeAll(b);
    result.addAll(b);
    return result;
}
function disjunctiveunion(a, b) {
    var intersection = intersection(a, b);
    var result = union(a, b);
    result.removeAll(intersection);
    return result;
}

set1 = [0,1,2,3];
set2 = [2,3,4,5];
// A △ B
result = disjunctiveunion(set1, set2);
writeDump(result); // outputs [0,1,4,5]

So there you go, hopefully these posts might help someone needing to compare arrays, or encourage you to have a look at the underlying Java methods that you could take advantage of.

Comments (0)
Add your comment