combinations.js (2064B)
1 import { factory } from '../../utils/factory.js'; 2 import { combinationsNumber } from '../../plain/number/combinations.js'; 3 var name = 'combinations'; 4 var dependencies = ['typed']; 5 export var createCombinations = /* #__PURE__ */factory(name, dependencies, _ref => { 6 var { 7 typed 8 } = _ref; 9 10 /** 11 * Compute the number of ways of picking `k` unordered outcomes from `n` 12 * possibilities. 13 * 14 * Combinations only takes integer arguments. 15 * The following condition must be enforced: k <= n. 16 * 17 * Syntax: 18 * 19 * math.combinations(n, k) 20 * 21 * Examples: 22 * 23 * math.combinations(7, 5) // returns 21 24 * 25 * See also: 26 * 27 * combinationsWithRep, permutations, factorial 28 * 29 * @param {number | BigNumber} n Total number of objects in the set 30 * @param {number | BigNumber} k Number of objects in the subset 31 * @return {number | BigNumber} Number of possible combinations. 32 */ 33 return typed(name, { 34 'number, number': combinationsNumber, 35 'BigNumber, BigNumber': function BigNumberBigNumber(n, k) { 36 var BigNumber = n.constructor; 37 var result, i; 38 var nMinusk = n.minus(k); 39 var one = new BigNumber(1); 40 41 if (!isPositiveInteger(n) || !isPositiveInteger(k)) { 42 throw new TypeError('Positive integer value expected in function combinations'); 43 } 44 45 if (k.gt(n)) { 46 throw new TypeError('k must be less than n in function combinations'); 47 } 48 49 result = one; 50 51 if (k.lt(nMinusk)) { 52 for (i = one; i.lte(nMinusk); i = i.plus(one)) { 53 result = result.times(k.plus(i)).dividedBy(i); 54 } 55 } else { 56 for (i = one; i.lte(k); i = i.plus(one)) { 57 result = result.times(nMinusk.plus(i)).dividedBy(i); 58 } 59 } 60 61 return result; 62 } // TODO: implement support for collection in combinations 63 64 }); 65 }); 66 /** 67 * Test whether BigNumber n is a positive integer 68 * @param {BigNumber} n 69 * @returns {boolean} isPositiveInteger 70 */ 71 72 function isPositiveInteger(n) { 73 return n.isInteger() && n.gte(0); 74 }