My friends invited me home to play the game of Secret Santa, where we are supposed to draw a lot & play the role of \'Santa\' for a friend in the group.
So, we write
I came across the built-in Subfactorial
function in the documentation and altered one of the examples to produce:
Remove[teleSecretSanta];
teleSecretSanta[dims_Integer] :=
With[{spec = Range[dims]},
With[{
perms = Permutations[spec],
casesToDelete = DiagonalMatrix[spec] /. {0 -> _}},
DeleteCases[perms, Alternatives @@ casesToDelete]
]
]
One can use Subfactorial
to check the function.
Length[teleSecretSanta[4]] == Subfactorial[4]
As in Mr.Wizard's answer, I suspect teleSecretSanta
can be optimized via SparseArray. However, I'm too drunk at the moment to attempt such shenanigans. (kidding... I'm actually too lazy and stupid.)