UNPKG

1.84 kBJavaScriptView Raw
1import { flatten } from '../../utils/array.js';
2import { factory } from '../../utils/factory.js';
3var name = 'setCartesian';
4var dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index', 'DenseMatrix'];
5export 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 /**
16 * Create the cartesian product of two (multi)sets.
17 * Multi-dimension arrays will be converted to single-dimension arrays 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 *
27 * See also:
28 *
29 * setUnion, setIntersect, setDifference, setPowerset
30 *
31 * @param {Array | Matrix} a1 A (multi)set
32 * @param {Array | Matrix} a2 A (multi)set
33 * @return {Array | Matrix} The cartesian product of two (multi)sets
34 */
35 return typed(name, {
36 'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) {
37 var result = [];
38
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
45 for (var i = 0; i < b1.length; i++) {
46 for (var j = 0; j < b2.length; j++) {
47 result.push([b1[i], b2[j]]);
48 }
49 }
50 } // return an array, if both inputs were arrays
51
52
53 if (Array.isArray(a1) && Array.isArray(a2)) {
54 return result;
55 } // return a matrix otherwise
56
57
58 return new DenseMatrix(result);
59 }
60 });
61});
\No newline at end of file