Secret Santa - Generating 'valid' permutations

前端 未结 6 831
不思量自难忘°
不思量自难忘° 2021-02-02 08:54

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

6条回答
  •  一整个雨季
    2021-02-02 09:27

    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.)

提交回复
热议问题