UNPKG

2.46 kBJavaScriptView Raw
1import { isInteger } from '../../utils/number.js';
2import { product } from '../../utils/product.js';
3import { factory } from '../../utils/factory.js';
4var name = 'permutations';
5var dependencies = ['typed', 'factorial'];
6export var createPermutations = /* #__PURE__ */factory(name, dependencies, (_ref) => {
7 var {
8 typed,
9 factorial
10 } = _ref;
11
12 /**
13 * Compute the number of ways of obtaining an ordered subset of `k` elements
14 * from a set of `n` elements.
15 *
16 * Permutations only takes integer arguments.
17 * The following condition must be enforced: k <= n.
18 *
19 * Syntax:
20 *
21 * math.permutations(n)
22 * math.permutations(n, k)
23 *
24 * Examples:
25 *
26 * math.permutations(5) // 120
27 * math.permutations(5, 3) // 60
28 *
29 * See also:
30 *
31 * combinations, combinationsWithRep, factorial
32 *
33 * @param {number | BigNumber} n The number of objects in total
34 * @param {number | BigNumber} [k] The number of objects in the subset
35 * @return {number | BigNumber} The number of permutations
36 */
37 return typed(name, {
38 'number | BigNumber': factorial,
39 'number, number': function numberNumber(n, k) {
40 if (!isInteger(n) || n < 0) {
41 throw new TypeError('Positive integer value expected in function permutations');
42 }
43
44 if (!isInteger(k) || k < 0) {
45 throw new TypeError('Positive integer value expected in function permutations');
46 }
47
48 if (k > n) {
49 throw new TypeError('second argument k must be less than or equal to first argument n');
50 } // Permute n objects, k at a time
51
52
53 return product(n - k + 1, n);
54 },
55 'BigNumber, BigNumber': function BigNumberBigNumber(n, k) {
56 var result, i;
57
58 if (!isPositiveInteger(n) || !isPositiveInteger(k)) {
59 throw new TypeError('Positive integer value expected in function permutations');
60 }
61
62 if (k.gt(n)) {
63 throw new TypeError('second argument k must be less than or equal to first argument n');
64 }
65
66 var one = n.mul(0).add(1);
67 result = one;
68
69 for (i = n.minus(k).plus(1); i.lte(n); i = i.plus(1)) {
70 result = result.times(i);
71 }
72
73 return result;
74 } // TODO: implement support for collection in permutations
75
76 });
77});
78/**
79 * Test whether BigNumber n is a positive integer
80 * @param {BigNumber} n
81 * @returns {boolean} isPositiveInteger
82 */
83
84function isPositiveInteger(n) {
85 return n.isInteger() && n.gte(0);
86}
\No newline at end of file