Files

122 lines
3.1 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
id: 5a23c84252665b21eecc8046
title: Симетрична різниця
challengeType: 5
forumTopicId: 16086
dashedName: symmetric-difference
---
# --description--
Дано два [set](https://rosettacode.org/wiki/set)s *A* та *B*, обчисліть $(A \\setminus B) \\cup (B \\setminus A).$ Тобто перерахуйте предмети, які містяться в *A* або *B*, але не в обох. Цей набір називається [симетричною різницею](https://en.wikipedia.org/wiki/Symmetric difference) *A* та *B*. Іншими словами: $(A \\cup B) \\setminus (A \\cap B)$ (набір предметів, які є в принаймні одному з *A* або *B* не входить в набір предметів, який є в обидвох *A* та *B*).
# --instructions--
Створіть функцію, яка приймає два масиви як параметри та повертає симетричну різницю. Відсортуйте отриманий масив перед поверненням.
# --hints--
`symmetricDifference` повинна бути функцією.
```js
assert(typeof symmetricDifference == 'function');
```
`symmetricDifference(["John", "Bob", "Mary", "Serena"], ["Jim", "Mary", "John", "Bob"])` має повернути масив.
```js
assert(
Array.isArray(
symmetricDifference(
['John', 'Bob', 'Mary', 'Serena'],
['Jim', 'Mary', 'John', 'Bob']
)
)
);
```
`symmetricDifference(["John", "Bob", "Mary", "Serena"], ["Jim", "Mary", "John", "Bob"])` має повернути `["Jim", "Serena"]`.
```js
assert.deepEqual(
symmetricDifference(
['John', 'Bob', 'Mary', 'Serena'],
['Jim', 'Mary', 'John', 'Bob']
),
['Jim', 'Serena']
);
```
`symmetricDifference([1, 2, 3], [3, 4])` має повернути `[1, 2, 4]`.
```js
assert.deepEqual(symmetricDifference([1, 2, 3], [3, 4]), [1, 2, 4]);
```
`symmetricDifference([1, 2, 3, 4, 5], [3, 4, 8, 7])` має повернути `[1, 2, 5, 7, 8]`.
```js
assert.deepEqual(symmetricDifference([1, 2, 3, 4, 5], [3, 4, 8, 7]), [
1,
2,
5,
7,
8
]);
```
`symmetricDifference([1, 2, 3, 4, 5, 6, 7, 8], [1, 3, 5, 6, 7, 8, 9])` має повернути `[2, 4, 9]`.
```js
assert.deepEqual(
symmetricDifference([1, 2, 3, 4, 5, 6, 7, 8], [1, 3, 5, 6, 7, 8, 9]),
[2, 4, 9]
);
```
`symmetricDifference([1, 2, 4, 7, 9], [2, 3, 7, 8, 9])` має повернути `[1, 3, 4, 8]`.
```js
assert.deepEqual(symmetricDifference([1, 2, 4, 7, 9], [2, 3, 7, 8, 9]), [
1,
3,
4,
8
]);
```
# --seed--
## --seed-contents--
```js
function symmetricDifference(A, B) {
}
```
# --solutions--
```js
function symmetricDifference(A, B) {
function relative_complement(A, B) {
return A.filter(function(elem) {
return B.indexOf(elem) == -1;
});
}
function unique(ary) {
var u = ary.concat().sort();
for (var i = 1; i < u.length; ) {
if (u[i - 1] === u[i]) u.splice(i, 1);
else i++;
}
return u;
}
return unique(
relative_complement(A, B).concat(relative_complement(B, A))
).sort();
}
```