UNPKG

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