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