setCartesian.js 1.9 KB

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