Skip to content

Commit 7a54fe5

Browse files
committed
Add a function to generate all derangements.
1 parent 2ad84aa commit 7a54fe5

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed

src/permutations.jl

+11
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#Permutations
22

33
export
4+
derangements,
45
levicivita,
56
multiset_permutations,
67
nthperm!,
@@ -134,6 +135,16 @@ function permutations(a, t::Integer)
134135
return Permutations(a, t)
135136
end
136137

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

138149
function nextpermutation(m, t, state)
139150
perm = [m[state[i]] for i in 1:t]

0 commit comments

Comments
 (0)