|
1 | 1 | #Permutations
|
2 | 2 |
|
3 | 3 | export
|
| 4 | + derangements, |
4 | 5 | levicivita,
|
5 | 6 | multiset_permutations,
|
6 | 7 | nthperm!,
|
@@ -136,6 +137,42 @@ function permutations(a, t::Integer)
|
136 | 137 | return Permutations(a, t)
|
137 | 138 | end
|
138 | 139 |
|
| 140 | +""" |
| 141 | + derangements(a) |
| 142 | +
|
| 143 | +Generate all derangements of an indexable object `a` in lexicographic order. |
| 144 | +Because the number of derangements can be very large, this function returns an iterator object. |
| 145 | +Use `collect(derangements(a))` to get an array of all derangements. |
| 146 | +Only works for `a` with defined length. |
| 147 | +
|
| 148 | +# Examples |
| 149 | +```jldoctest |
| 150 | +julia> derangements("julia") |> collect |
| 151 | +44-element Vector{Vector{Char}}: |
| 152 | + ['u', 'j', 'i', 'a', 'l'] |
| 153 | + ['u', 'j', 'a', 'l', 'i'] |
| 154 | + ['u', 'l', 'j', 'a', 'i'] |
| 155 | + ['u', 'l', 'i', 'a', 'j'] |
| 156 | + ['u', 'l', 'a', 'j', 'i'] |
| 157 | + ['u', 'i', 'j', 'a', 'l'] |
| 158 | + ['u', 'i', 'a', 'j', 'l'] |
| 159 | + ['u', 'i', 'a', 'l', 'j'] |
| 160 | + ['u', 'a', 'j', 'l', 'i'] |
| 161 | + ['u', 'a', 'i', 'j', 'l'] |
| 162 | + ⋮ |
| 163 | + ['a', 'j', 'i', 'l', 'u'] |
| 164 | + ['a', 'l', 'j', 'u', 'i'] |
| 165 | + ['a', 'l', 'u', 'j', 'i'] |
| 166 | + ['a', 'l', 'i', 'j', 'u'] |
| 167 | + ['a', 'l', 'i', 'u', 'j'] |
| 168 | + ['a', 'i', 'j', 'u', 'l'] |
| 169 | + ['a', 'i', 'j', 'l', 'u'] |
| 170 | + ['a', 'i', 'u', 'j', 'l'] |
| 171 | + ['a', 'i', 'u', 'l', 'j'] |
| 172 | +``` |
| 173 | +""" |
| 174 | +derangements(a) = (d for d in multiset_permutations(a, length(a)) if all(t -> t[1] != t[2], zip(a, d))) |
| 175 | + |
139 | 176 |
|
140 | 177 | function nextpermutation(m, t, state)
|
141 | 178 | perm = [m[state[i]] for i in 1:t]
|
@@ -249,8 +286,8 @@ julia> collect(multiset_permutations([1,1,2], 3))
|
249 | 286 | ```
|
250 | 287 | """
|
251 | 288 | function multiset_permutations(a, t::Integer)
|
252 |
| - m = unique(collect(a)) |
253 |
| - f = [sum([c == x for c in a]) for x in m] |
| 289 | + m = unique(a) |
| 290 | + f = [sum(c == x for c in a)::Int for x in m] |
254 | 291 | multiset_permutations(m, f, t)
|
255 | 292 | end
|
256 | 293 |
|
|
0 commit comments