Skip to content

Commit 38fc5c4

Browse files
Sedictiousararslan
authored andcommitted
Add partial derangements (#78)
1 parent 1d0f0d2 commit 38fc5c4

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ This library provides the following functions:
1818
- `combinations(a,n)`: returns all combinations of `n` elements of indexable object `a`;
1919
- `combinations(a)`: returns combinations of all order by chaining calls to `combinations(a,n)`;
2020
- `derangement(n)`/`subfactorial(n)`: returns the number of permutations of n with no fixed points; always returns a `BigInt`;
21+
- `partialderangement(n, k)`: returns the number of permutations of n with exactly k fixed points; always returns a `BigInt`;
2122
- `doublefactorial(n)`: returns the double factorial n!!; always returns a `BigInt`;
2223
- `fibonaccinum(n)`: the n-th Fibonacci number; always returns a `BigInt`;
2324
- `hyperfactorial(n)`: the n-th hyperfactorial, i.e. prod([i^i for i = 2:n]; always returns a `BigInt`;

src/factorials.jl

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
export
44
derangement,
5+
partialderangement,
56
factorial,
67
subfactorial,
78
doublefactorial,
@@ -52,6 +53,23 @@ function doublefactorial(n::Integer)
5253
return z[]
5354
end
5455

56+
"""
57+
partialderangement(n, k)
58+
59+
Compute the number of permutations of `n` with exactly k fixed points.
60+
"""
61+
function partialderangement(n::Integer, k::Integer)
62+
if n < 0
63+
throw(DomainError(n))
64+
end
65+
if k < 0 || k > n
66+
throw(DomainError(k))
67+
end
68+
a = BigInt(n)
69+
b = BigInt(k)
70+
return subfactorial(a - b) * binomial(a, b)
71+
end
72+
5573
# Hyperfactorial
5674
hyperfactorial(n::Integer) = prod(i->i^i, BigInt(2):n)
5775

test/factorials.jl

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,11 @@
1111
@test derangement(4) == subfactorial(4) == 9
1212
@test derangement(24) == parse(BigInt,"228250211305338670494289")
1313

14+
# partialderangement
15+
@test partialderangement(7, 3) == 315
16+
@test_throws DomainError partialderangement(8, 9)
17+
@test_throws DomainError partialderangement(-8, 0)
18+
1419
# doublefactorial
1520
@test doublefactorial(70) == parse(BigInt,"355044260642859198243475901411974413130137600000000")
1621
@test_throws DomainError doublefactorial(-1)

0 commit comments

Comments
 (0)