setIntersect.js 2.4 KB

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