UNPKG

2.74 kBJavaScriptView Raw
1import { factory } from '../../utils/factory'
2import { isInteger } from '../../utils/number'
3import { product } from '../../utils/product'
4
5const name = 'combinationsWithRep'
6const dependencies = ['typed']
7
8export const createCombinationsWithRep = /* #__PURE__ */ factory(name, dependencies, ({ typed }) => {
9 /**
10 * Compute the number of ways of picking `k` unordered outcomes from `n`
11 * possibilities, allowing individual outcomes to be repeated more than once.
12 *
13 * CombinationsWithRep only takes integer arguments.
14 * The following condition must be enforced: k <= n + k -1.
15 *
16 * Syntax:
17 *
18 * math.combinationsWithRep(n, k)
19 *
20 * Examples:
21 *
22 * math.combinationsWithRep(7, 5) // returns 462
23 *
24 * See also:
25 *
26 * combinations, permutations, factorial
27 *
28 * @param {number | BigNumber} n Total number of objects in the set
29 * @param {number | BigNumber} k Number of objects in the subset
30 * @return {number | BigNumber} Number of possible combinations with replacement.
31 */
32 return typed(name, {
33 'number, number': function (n, k) {
34 if (!isInteger(n) || n < 0) {
35 throw new TypeError('Positive integer value expected in function combinationsWithRep')
36 }
37 if (!isInteger(k) || k < 0) {
38 throw new TypeError('Positive integer value expected in function combinationsWithRep')
39 }
40 if (n < 1) {
41 throw new TypeError('k must be less than or equal to n + k - 1')
42 }
43
44 if (k < n - 1) {
45 const prodrange = product(n, n + k - 1)
46 return prodrange / product(1, k)
47 }
48 const prodrange = product(k + 1, n + k - 1)
49 return prodrange / product(1, n - 1)
50 },
51
52 'BigNumber, BigNumber': function (n, k) {
53 const BigNumber = n.constructor
54 let result, i
55 const one = new BigNumber(1)
56 const nMinusOne = n.minus(one)
57
58 if (!isPositiveInteger(n) || !isPositiveInteger(k)) {
59 throw new TypeError('Positive integer value expected in function combinationsWithRep')
60 }
61 if (n.lt(one)) {
62 throw new TypeError('k must be less than or equal to n + k - 1 in function combinationsWithRep')
63 }
64
65 result = one
66 if (k.lt(nMinusOne)) {
67 for (i = one; i.lte(nMinusOne); i = i.plus(one)) {
68 result = result.times(k.plus(i)).dividedBy(i)
69 }
70 } else {
71 for (i = one; i.lte(k); i = i.plus(one)) {
72 result = result.times(nMinusOne.plus(i)).dividedBy(i)
73 }
74 }
75
76 return result
77 }
78 })
79})
80
81/**
82 * Test whether BigNumber n is a positive integer
83 * @param {BigNumber} n
84 * @returns {boolean} isPositiveInteger
85 */
86function isPositiveInteger (n) {
87 return n.isInteger() && n.gte(0)
88}