UNPKG

2.17 kBJavaScriptView Raw
1import { flatten, generalize, identify } from '../../utils/array.js';
2import { factory } from '../../utils/factory.js';
3var name = 'setIntersect';
4var dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index', 'DenseMatrix'];
5export var createSetIntersect = /* #__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 intersection of two (multi)sets.
17 * Multi-dimension arrays will be converted to single-dimension arrays before the operation.
18 *
19 * Syntax:
20 *
21 * math.setIntersect(set1, set2)
22 *
23 * Examples:
24 *
25 * math.setIntersect([1, 2, 3, 4], [3, 4, 5, 6]) // returns [3, 4]
26 * math.setIntersect([[1, 2], [3, 4]], [[3, 4], [5, 6]]) // returns [3, 4]
27 *
28 * See also:
29 *
30 * setUnion, setDifference
31 *
32 * @param {Array | Matrix} a1 A (multi)set
33 * @param {Array | Matrix} a2 A (multi)set
34 * @return {Array | Matrix} The intersection 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 || subset(size(a2), new Index(0)) === 0) {
41 // of any of them is empty, return empty
42 result = [];
43 } else {
44 var b1 = identify(flatten(Array.isArray(a1) ? a1 : a1.toArray()).sort(compareNatural));
45 var b2 = identify(flatten(Array.isArray(a2) ? a2 : a2.toArray()).sort(compareNatural));
46 result = [];
47
48 for (var i = 0; i < b1.length; i++) {
49 for (var j = 0; j < b2.length; j++) {
50 if (compareNatural(b1[i].value, b2[j].value) === 0 && b1[i].identifier === b2[j].identifier) {
51 // the identifier is always a decimal int
52 result.push(b1[i]);
53 break;
54 }
55 }
56 }
57 } // return an array, if both inputs were arrays
58
59
60 if (Array.isArray(a1) && Array.isArray(a2)) {
61 return generalize(result);
62 } // return a matrix otherwise
63
64
65 return new DenseMatrix(generalize(result));
66 }
67 });
68});
\No newline at end of file