UNPKG

1.95 kBJavaScriptView Raw
1'use strict'
2
3const flatten = require('../../utils/array').flatten
4
5function factory (type, config, load, typed) {
6 const MatrixIndex = load(require('../../type/matrix/MatrixIndex'))
7 const DenseMatrix = load(require('../../type/matrix/DenseMatrix'))
8 const size = load(require('../matrix/size'))
9 const subset = load(require('../matrix/subset'))
10 const 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 const setCartesian = typed('setCartesian', {
33 'Array | Matrix, Array | Matrix': function (a1, a2) {
34 let result = []
35
36 if (subset(size(a1), new MatrixIndex(0)) !== 0 && subset(size(a2), new MatrixIndex(0)) !== 0) { // if any of them is empty, return empty
37 const b1 = flatten(Array.isArray(a1) ? a1 : a1.toArray()).sort(compareNatural)
38 const b2 = flatten(Array.isArray(a2) ? a2 : a2.toArray()).sort(compareNatural)
39 result = []
40 for (let i = 0; i < b1.length; i++) {
41 for (let j = 0; j < b2.length; j++) {
42 result.push([b1[i], b2[j]])
43 }
44 }
45 }
46 // return an array, if both inputs were arrays
47 if (Array.isArray(a1) && Array.isArray(a2)) {
48 return result
49 }
50 // return a matrix otherwise
51 return new DenseMatrix(result)
52 }
53 })
54
55 return setCartesian
56}
57
58exports.name = 'setCartesian'
59exports.factory = factory