Search This Blog

2024/04/08

Javascript Algorithm:Symmetric Difference between multiple sets(FreeCodeCamp)

Find the Symmetric Difference:
The mathematical term symmetric difference (△ or ⊕) of two sets is the set of
elements which are in either of the two sets but not in both. For example, for
sets A = {1, 2, 3} and B = {2, 3, 4}, A △ B = {1, 4}.

Symmetric difference is a binary operation, which means it operates on only two
elements. So to evaluate an expression involving symmetric differences among
three elements (A △ B △ C), you must complete one operation at a time. Thus, for
sets A and B above, and C = {2, 3}, A △ B △ C = (A △ B) △ C = {1, 4} △ {2, 3} =
{1, 2, 3, 4}.

Create a function that takes two or more arrays and returns an array of their
symmetric difference. The returned array must contain only unique values (no
duplicates).

Test Cases:
1) sym([1, 2, 3], [5, 2, 1, 4]) should return [3, 4, 5].
2) sym([1, 2, 3], [5, 2, 1, 4]) should contain only three elements.
3) sym([1, 2, 3, 3], [5, 2, 1, 4]) should return [3, 4, 5].
4) sym([1, 2, 3, 3], [5, 2, 1, 4]) should contain only three elements.
5) sym([1, 2, 3], [5, 2, 1, 4, 5]) should return [3, 4, 5].
6) sym([1, 2, 3], [5, 2, 1, 4, 5]) should contain only three elements.
7) sym([1, 2, 5], [2, 3, 5], [3, 4, 5]) should return [1, 4, 5].
8) sym([1, 2, 5], [2, 3, 5], [3, 4, 5]) should contain only three elements.
9) sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]) should return [1, 4, 5].
10) sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]) should contain only three
elements.
11) sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3]) should return
[2, 3, 4, 6, 7].
12) sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3]) should contain
only five elements.
13) sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8],
[1]) should return [1, 2, 4, 5, 6, 7, 8, 9].
14) sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8],
[1]) should contain only eight elements.

Solution:
function BinarySymmetricDifference(a, b) {
let c = [...a, ...b];

//keep unique elements only
let set = new Set(c);
c = Array.from(set);

let d = [];

a.forEach((m) => {
if (b.includes(m)) {
if (!d.includes(m)) {
d.push(m);
}
}
});

let e = c.filter((m) => {
return !d.includes(m);
});
return e;
}

function sym(...args) {
let initialArray = args[0]
for (let i = 1; i < args.length; i++) {
initialArray = BinarySymmetricDifference(initialArray,args[i])
}
return initialArray
}

let diff = sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]);
console.log(diff);

No comments:

Post a Comment