UNPKG

1.98 kBJavaScriptView Raw
1'use strict';
2
3var flatten = require('../../utils/array').flatten;
4
5function factory(type, config, load, typed) {
6 var MatrixIndex = load(require('../../type/matrix/MatrixIndex'));
7 var DenseMatrix = load(require('../../type/matrix/DenseMatrix'));
8 var size = load(require('../matrix/size'));
9 var subset = load(require('../matrix/subset'));
10 var compareNatural = load(require('../relational/compareNatural'));
11
12 /**
13 * Create the cartesian product of two (multi)sets.
14 * Multi-dimension arrays will be converted to single-dimension arrays before the operation.
15 *
16 * Syntax:
17 *
18 * math.setCartesian(set1, set2)
19 *
20 * Examples:
21 *
22 * math.setCartesian([1, 2], [3, 4]) // returns [[1, 3], [1, 4], [2, 3], [2, 4]]
23 *
24 * See also:
25 *
26 * setUnion, setIntersect, setDifference, setPowerset
27 *
28 * @param {Array | Matrix} a1 A (multi)set
29 * @param {Array | Matrix} a2 A (multi)set
30 * @return {Array | Matrix} The cartesian product of two (multi)sets
31 */
32 var setCartesian = typed('setCartesian', {
33 'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) {
34 var result = [];
35
36 if (subset(size(a1), new MatrixIndex(0)) !== 0 && subset(size(a2), new MatrixIndex(0)) !== 0) {
37 // if any of them is empty, return empty
38 var b1 = flatten(Array.isArray(a1) ? a1 : a1.toArray()).sort(compareNatural);
39 var b2 = flatten(Array.isArray(a2) ? a2 : a2.toArray()).sort(compareNatural);
40 result = [];
41 for (var i = 0; i < b1.length; i++) {
42 for (var j = 0; j < b2.length; j++) {
43 result.push([b1[i], b2[j]]);
44 }
45 }
46 }
47 // return an array, if both inputs were arrays
48 if (Array.isArray(a1) && Array.isArray(a2)) {
49 return result;
50 }
51 // return a matrix otherwise
52 return new DenseMatrix(result);
53 }
54 });
55
56 return setCartesian;
57}
58
59exports.name = 'setCartesian';
60exports.factory = factory;
\No newline at end of file