Skip to content

Commit

Permalink
Add partial derangements (#78)
Browse files Browse the repository at this point in the history
  • Loading branch information
Sedictious authored and ararslan committed May 16, 2019
1 parent 1d0f0d2 commit 38fc5c4
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ This library provides the following functions:
- `combinations(a,n)`: returns all combinations of `n` elements of indexable object `a`;
- `combinations(a)`: returns combinations of all order by chaining calls to `combinations(a,n)`;
- `derangement(n)`/`subfactorial(n)`: returns the number of permutations of n with no fixed points; always returns a `BigInt`;
- `partialderangement(n, k)`: returns the number of permutations of n with exactly k fixed points; always returns a `BigInt`;
- `doublefactorial(n)`: returns the double factorial n!!; always returns a `BigInt`;
- `fibonaccinum(n)`: the n-th Fibonacci number; always returns a `BigInt`;
- `hyperfactorial(n)`: the n-th hyperfactorial, i.e. prod([i^i for i = 2:n]; always returns a `BigInt`;
Expand Down
18 changes: 18 additions & 0 deletions src/factorials.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

export
derangement,
partialderangement,
factorial,
subfactorial,
doublefactorial,
Expand Down Expand Up @@ -52,6 +53,23 @@ function doublefactorial(n::Integer)
return z[]
end

"""
partialderangement(n, k)
Compute the number of permutations of `n` with exactly k fixed points.
"""
function partialderangement(n::Integer, k::Integer)
if n < 0
throw(DomainError(n))
end
if k < 0 || k > n
throw(DomainError(k))
end
a = BigInt(n)
b = BigInt(k)
return subfactorial(a - b) * binomial(a, b)
end

# Hyperfactorial
hyperfactorial(n::Integer) = prod(i->i^i, BigInt(2):n)

Expand Down
5 changes: 5 additions & 0 deletions test/factorials.jl
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@
@test derangement(4) == subfactorial(4) == 9
@test derangement(24) == parse(BigInt,"228250211305338670494289")

# partialderangement
@test partialderangement(7, 3) == 315
@test_throws DomainError partialderangement(8, 9)
@test_throws DomainError partialderangement(-8, 0)

# doublefactorial
@test doublefactorial(70) == parse(BigInt,"355044260642859198243475901411974413130137600000000")
@test_throws DomainError doublefactorial(-1)
Expand Down

0 comments on commit 38fc5c4

Please sign in to comment.