UNPKG

2.42 kBJavaScriptView Raw
1import { flatten, generalize, identify } from '../../utils/array.js';
2import { factory } from '../../utils/factory.js';
3var name = 'setDifference';
4var dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index', 'DenseMatrix'];
5export var createSetDifference = /* #__PURE__ */factory(name, dependencies, (_ref) => {
6 var {
7 typed,
8 size,
9 subset,
10 compareNatural,
11 Index,
12 DenseMatrix
13 } = _ref;
14
15 /**
16 * Create the difference of two (multi)sets: every element of set1, that is not the element of set2.
17 * Multi-dimension arrays will be converted to single-dimension arrays before the operation.
18 *
19 * Syntax:
20 *
21 * math.setDifference(set1, set2)
22 *
23 * Examples:
24 *
25 * math.setDifference([1, 2, 3, 4], [3, 4, 5, 6]) // returns [1, 2]
26 * math.setDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]]) // returns [1, 2]
27 *
28 * See also:
29 *
30 * setUnion, setIntersect, setSymDifference
31 *
32 * @param {Array | Matrix} a1 A (multi)set
33 * @param {Array | Matrix} a2 A (multi)set
34 * @return {Array | Matrix} The difference of two (multi)sets
35 */
36 return typed(name, {
37 'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) {
38 var result;
39
40 if (subset(size(a1), new Index(0)) === 0) {
41 // empty-anything=empty
42 result = [];
43 } else if (subset(size(a2), new Index(0)) === 0) {
44 // anything-empty=anything
45 return flatten(a1.toArray());
46 } else {
47 var b1 = identify(flatten(Array.isArray(a1) ? a1 : a1.toArray()).sort(compareNatural));
48 var b2 = identify(flatten(Array.isArray(a2) ? a2 : a2.toArray()).sort(compareNatural));
49 result = [];
50 var inb2;
51
52 for (var i = 0; i < b1.length; i++) {
53 inb2 = false;
54
55 for (var j = 0; j < b2.length; j++) {
56 if (compareNatural(b1[i].value, b2[j].value) === 0 && b1[i].identifier === b2[j].identifier) {
57 // the identifier is always a decimal int
58 inb2 = true;
59 break;
60 }
61 }
62
63 if (!inb2) {
64 result.push(b1[i]);
65 }
66 }
67 } // return an array, if both inputs were arrays
68
69
70 if (Array.isArray(a1) && Array.isArray(a2)) {
71 return generalize(result);
72 } // return a matrix otherwise
73
74
75 return new DenseMatrix(generalize(result));
76 }
77 });
78});
\No newline at end of file