Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Derangements #150

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/permutations.jl
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#Permutations

export
derangements,
levicivita,
multiset_permutations,
nthperm!,
Expand Down Expand Up @@ -93,6 +94,16 @@ function permutations(a, t::Integer)
return Permutations(a, t)
end

"""
derangements(a)

Generate all derangements of an indexable object `a` in lexicographic order.
Because the number of derangements can be very large, this function returns an iterator object.
Use `collect(derangements(a))` to get an array of all derangements.
Only works for `a` with defined length.
"""
derangements(a) = (d for d in multiset_permutations(a, length(a)) if all(t -> t[1] != t[2], zip(a, d)))


function nextpermutation(m, t, state)
perm = [m[state[i]] for i in 1:t]
Expand Down
7 changes: 7 additions & 0 deletions test/permutations.jl
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,13 @@ end
@test collect(multiset_permutations("", -1)) == Any[]
@test length(multiset_permutations("aaaaaaaaaaaaaaaaaaaaab", 21)) == 22

# derangements
@test collect(derangements(Int[])) == [[]]
@test length(collect(derangements(1:4))) == 9
@test length(collect(derangements(1:8))) == derangement(8) == 14833
@test collect(derangements([1, 1, 2, 2])) == [[2, 2, 1, 1]]
@test collect(map(join, derangements("abbac"))) == ["baacb", "bacba", "bcaba", "caabb"]

#nthperm!
for n = 0:7, k = 1:factorial(n)
p = nthperm!([1:n;], k)
Expand Down
Loading