setDifference.js 2.7 KB

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