mathjs
Version:
Math.js is an extensive math library for JavaScript and Node.js. It features a flexible expression parser with support for symbolic computation, comes with a large set of built-in functions and constants, and offers an integrated solution to work with dif
55 lines (48 loc) • 1.63 kB
JavaScript
;
var flatten = require('../../utils/array').flatten;
function factory(type, config, load, typed) {
var compareNatural = load(require('../relational/compareNatural'));
var MatrixIndex = load(require('../../type/matrix/MatrixIndex'));
var size = load(require('../matrix/size'));
var subset = load(require('../matrix/subset'));
/**
* Count the multiplicity of an element in a multiset.
* A multi-dimension array will be converted to a single-dimension array before the operation.
*
* Syntax:
*
* math.setMultiplicity(element, set)
*
* Examples:
*
* math.setMultiplicity(1, [1, 2, 2, 4]) // returns 1
* math.setMultiplicity(2, [1, 2, 2, 4]) // returns 2
*
* See also:
*
* setDistinct, setSize
*
* @param {number | BigNumber | Fraction | Complex} e An element in the multiset
* @param {Array | Matrix} a A multiset
* @return {number} The number of how many times the multiset contains the element
*/
var setMultiplicity = typed('setMultiplicity', {
'number | BigNumber | Fraction | Complex, Array | Matrix': function numberBigNumberFractionComplexArrayMatrix(e, a) {
if (subset(size(a), new MatrixIndex(0)) === 0) {
// if empty, return 0
return 0;
}
var b = flatten(Array.isArray(a) ? a : a.toArray());
var count = 0;
for (var i = 0; i < b.length; i++) {
if (compareNatural(b[i], e) === 0) {
count++;
}
}
return count;
}
});
return setMultiplicity;
}
exports.name = 'setMultiplicity';
exports.factory = factory;