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