Find all derangements for $n=4$ and $n=5$
Solution for $n=4$
I know there are 9 possibilities
$(2,1,4,3), (2,3,4,1), (2,4,1,3), (3,1,4,2),(3,4,1,2), (3,4,2,1) (4,1,2,3),(4,3,1,2), (4,3,2,1)$
Solution for $n=5$
I know there are 44 of them, I am wondering if someone had a link to a list of them, or possibly a program that would spit them out, or could help me in general, thanks!
These kind of things are actually really easy to find with Constraint programming.
For a permutation of length n we got the following constraints for a list:
- The list has to have length(n)
- Any number x must be in range 1..n
- All elements must different
Looking at a derangement of length n we got the following constraints:
- Be a permutation
- Have no fixed points
We can put all of this quite fast together in Prolog with:
With derangement(L,N) we can now simply generate derangements of a certain a size or all of them (of a certain size) with findDerangements(N,Ls).
You can try it out here ideone link - source