Suppose I have an array of integers int a[] = {0, 1, ... N-1}, where N is the size of a. Now I need to generate all permutations of a s that a[i] != i for all 0 <= i < N. How would you do that?
Suppose I have an array of integers int a[] = {0, 1, … N-1}
Share
Here’s some C++ implementing an algorithm based on a bijective proof of the recurrence
where
!nis the number of derangements ofnitems.On my machine, I get
which IMHO is a wash. Probably there are improvements to be made on both sides (e.g., reimplement
next_permutationwith the derangement test that scans only the elements that changed); that’s left as an exercise to the reader.