setCartesian.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.createSetCartesian = void 0;
  6. var _array = require("../../utils/array.js");
  7. var _factory = require("../../utils/factory.js");
  8. var name = 'setCartesian';
  9. var dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index', 'DenseMatrix'];
  10. var createSetCartesian = /* #__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 cartesian product of two (multi)sets.
  19. * Multi-dimension arrays will be converted to single-dimension arrays
  20. * and the values will be sorted in ascending order before the operation.
  21. *
  22. * Syntax:
  23. *
  24. * math.setCartesian(set1, set2)
  25. *
  26. * Examples:
  27. *
  28. * math.setCartesian([1, 2], [3, 4]) // returns [[1, 3], [1, 4], [2, 3], [2, 4]]
  29. * math.setCartesian([4, 3], [2, 1]) // returns [[3, 1], [3, 2], [4, 1], [4, 2]]
  30. *
  31. * See also:
  32. *
  33. * setUnion, setIntersect, setDifference, setPowerset
  34. *
  35. * @param {Array | Matrix} a1 A (multi)set
  36. * @param {Array | Matrix} a2 A (multi)set
  37. * @return {Array | Matrix} The cartesian product of two (multi)sets
  38. */
  39. return typed(name, {
  40. 'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) {
  41. var result = [];
  42. if (subset(size(a1), new Index(0)) !== 0 && subset(size(a2), new Index(0)) !== 0) {
  43. // if any of them is empty, return empty
  44. var b1 = (0, _array.flatten)(Array.isArray(a1) ? a1 : a1.toArray()).sort(compareNatural);
  45. var b2 = (0, _array.flatten)(Array.isArray(a2) ? a2 : a2.toArray()).sort(compareNatural);
  46. result = [];
  47. for (var i = 0; i < b1.length; i++) {
  48. for (var j = 0; j < b2.length; j++) {
  49. result.push([b1[i], b2[j]]);
  50. }
  51. }
  52. }
  53. // return an array, if both inputs were arrays
  54. if (Array.isArray(a1) && Array.isArray(a2)) {
  55. return result;
  56. }
  57. // return a matrix otherwise
  58. return new DenseMatrix(result);
  59. }
  60. });
  61. });
  62. exports.createSetCartesian = createSetCartesian;