1 | import { factory } from '../../utils/factory'
|
2 | import { isInteger } from '../../utils/number'
|
3 | import { product } from '../../utils/product'
|
4 |
|
5 | const name = 'combinationsWithRep'
|
6 | const dependencies = ['typed']
|
7 |
|
8 | export const createCombinationsWithRep = factory(name, dependencies, ({ typed }) => {
|
9 | |
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
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 |
|
83 |
|
84 |
|
85 |
|
86 | function isPositiveInteger (n) {
|
87 | return n.isInteger() && n.gte(0)
|
88 | }
|