UNPKG

1.77 kBJavaScriptView Raw
1import { flatten } from '../../utils/array'
2import { factory } from '../../utils/factory'
3
4const name = 'setCartesian'
5const dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index', 'DenseMatrix']
6
7export const createSetCartesian = /* #__PURE__ */ factory(name, dependencies, ({ typed, size, subset, compareNatural, Index, DenseMatrix }) => {
8 /**
9 * Create the cartesian product of two (multi)sets.
10 * Multi-dimension arrays will be converted to single-dimension arrays before the operation.
11 *
12 * Syntax:
13 *
14 * math.setCartesian(set1, set2)
15 *
16 * Examples:
17 *
18 * math.setCartesian([1, 2], [3, 4]) // returns [[1, 3], [1, 4], [2, 3], [2, 4]]
19 *
20 * See also:
21 *
22 * setUnion, setIntersect, setDifference, setPowerset
23 *
24 * @param {Array | Matrix} a1 A (multi)set
25 * @param {Array | Matrix} a2 A (multi)set
26 * @return {Array | Matrix} The cartesian product of two (multi)sets
27 */
28 return typed(name, {
29 'Array | Matrix, Array | Matrix': function (a1, a2) {
30 let result = []
31
32 if (subset(size(a1), new Index(0)) !== 0 && subset(size(a2), new Index(0)) !== 0) { // if any of them is empty, return empty
33 const b1 = flatten(Array.isArray(a1) ? a1 : a1.toArray()).sort(compareNatural)
34 const b2 = flatten(Array.isArray(a2) ? a2 : a2.toArray()).sort(compareNatural)
35 result = []
36 for (let i = 0; i < b1.length; i++) {
37 for (let j = 0; j < b2.length; j++) {
38 result.push([b1[i], b2[j]])
39 }
40 }
41 }
42 // return an array, if both inputs were arrays
43 if (Array.isArray(a1) && Array.isArray(a2)) {
44 return result
45 }
46 // return a matrix otherwise
47 return new DenseMatrix(result)
48 }
49 })
50})