UNPKG

1.58 kBJavaScriptView Raw
1'use strict'
2
3const deepForEach = require('../../utils/collection/deepForEach')
4
5function factory (type, config, load, typed) {
6 const add = load(require('../arithmetic/add'))
7 const multiply = load(require('../arithmetic/multiply'))
8 const divide = load(require('../arithmetic/divide'))
9 const factorial = load(require('../probability/factorial'))
10 const isInteger = load(require('../utils/isInteger'))
11 const isPositive = load(require('../utils/isPositive'))
12
13 /**
14 * Multinomial Coefficients compute the number of ways of picking a1, a2, ..., ai unordered outcomes from `n` possibilities.
15 *
16 * multinomial takes one array of integers as an argument.
17 * The following condition must be enforced: every ai <= 0
18 *
19 * Syntax:
20 *
21 * math.multinomial(a) // a is an array type
22 *
23 * Examples:
24 *
25 * math.multinomial([1,2,1]) // returns 12
26 *
27 * See also:
28 *
29 * combinations, factorial
30 *
31 * @param {number[] | BigNumber[]} a Integer numbers of objects in the subset
32 * @return {Number | BigNumber} Multinomial coefficient.
33 */
34 return typed('multinomial', {
35 'Array | Matrix': function (a) {
36 let sum = 0
37 let denom = 1
38
39 deepForEach(a, function (ai) {
40 if (!isInteger(ai) || !isPositive(ai)) {
41 throw new TypeError('Positive integer value expected in function multinomial')
42 }
43 sum = add(sum, ai)
44 denom = multiply(denom, factorial(ai))
45 })
46
47 return divide(factorial(sum), denom)
48 }
49 })
50}
51
52exports.name = 'multinomial'
53exports.factory = factory