forked from josdejong/mathjs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetIntersect.js
More file actions
55 lines (53 loc) · 2.04 KB
/
setIntersect.js
File metadata and controls
55 lines (53 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { flatten, generalize, identify } from '../../utils/array.js'
import { factory } from '../../utils/factory.js'
const name = 'setIntersect'
const dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index', 'DenseMatrix']
export const createSetIntersect = /* #__PURE__ */ factory(name, dependencies, ({ typed, size, subset, compareNatural, Index, DenseMatrix }) => {
/**
* Create the intersection of two (multi)sets.
* Multi-dimension arrays will be converted to single-dimension arrays before the operation.
*
* Syntax:
*
* math.setIntersect(set1, set2)
*
* Examples:
*
* math.setIntersect([1, 2, 3, 4], [3, 4, 5, 6]) // returns [3, 4]
* math.setIntersect([[1, 2], [3, 4]], [[3, 4], [5, 6]]) // returns [3, 4]
*
* See also:
*
* setUnion, setDifference
*
* @param {Array | Matrix} a1 A (multi)set
* @param {Array | Matrix} a2 A (multi)set
* @return {Array | Matrix} The intersection of two (multi)sets
*/
return typed(name, {
'Array | Matrix, Array | Matrix': function (a1, a2) {
let result
if (subset(size(a1), new Index(0)) === 0 || subset(size(a2), new Index(0)) === 0) { // of any of them is empty, return empty
result = []
} else {
const b1 = identify(flatten(Array.isArray(a1) ? a1 : a1.toArray()).sort(compareNatural))
const b2 = identify(flatten(Array.isArray(a2) ? a2 : a2.toArray()).sort(compareNatural))
result = []
for (let i = 0; i < b1.length; i++) {
for (let j = 0; j < b2.length; j++) {
if (compareNatural(b1[i].value, b2[j].value) === 0 && b1[i].identifier === b2[j].identifier) { // the identifier is always a decimal int
result.push(b1[i])
break
}
}
}
}
// return an array, if both inputs were arrays
if (Array.isArray(a1) && Array.isArray(a2)) {
return generalize(result)
}
// return a matrix otherwise
return new DenseMatrix(generalize(result))
}
})
})