Take a finite set $S$ (i.e., a list). An involutive permutation is one that squares to the identity. How can we generate all such permutations efficiently, that is, without generating all permutations first, and eliminating the non-involutive ones?
For example, the code below generates all involutive permutations on the set {1,2,3,4}
, by first generating all permutations:
With[{perm = Permutations[Range[4]]}, perm[[Flatten@Position[Map[Apply[ReplaceAll], Transpose[{perm, Thread /@ Thread[ConstantArray[Range[4], 4!] -> perm]}]], Range[4]]]]]
The code returns 10 out of the 24 permutations of {1,2,3,4}
. The reduction for larger lists is more extreme (e.g., 76 vs 720 for a list of size 6). I need to consider a rather large list, so generating all permutations first is unfeasible. How can we make the calculation as efficient as possible?