setIntersect.js 2.1 KB

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