UNPKG

1.44 kBJavaScriptView Raw
1import { flatten } from '../../utils/array'
2import { factory } from '../../utils/factory'
3
4const name = 'setMultiplicity'
5const dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index']
6
7export const createSetMultiplicity = /* #__PURE__ */ factory(name, dependencies, ({ typed, size, subset, compareNatural, Index }) => {
8 /**
9 * Count the multiplicity of an element in a multiset.
10 * A multi-dimension array will be converted to a single-dimension array before the operation.
11 *
12 * Syntax:
13 *
14 * math.setMultiplicity(element, set)
15 *
16 * Examples:
17 *
18 * math.setMultiplicity(1, [1, 2, 2, 4]) // returns 1
19 * math.setMultiplicity(2, [1, 2, 2, 4]) // returns 2
20 *
21 * See also:
22 *
23 * setDistinct, setSize
24 *
25 * @param {number | BigNumber | Fraction | Complex} e An element in the multiset
26 * @param {Array | Matrix} a A multiset
27 * @return {number} The number of how many times the multiset contains the element
28 */
29 return typed(name, {
30 'number | BigNumber | Fraction | Complex, Array | Matrix': function (e, a) {
31 if (subset(size(a), new Index(0)) === 0) { // if empty, return 0
32 return 0
33 }
34 const b = flatten(Array.isArray(a) ? a : a.toArray())
35 let count = 0
36 for (let i = 0; i < b.length; i++) {
37 if (compareNatural(b[i], e) === 0) {
38 count++
39 }
40 }
41 return count
42 }
43 })
44})