setDifference.js 2.4 KB

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