Secret Santa - Generating 'valid' permutations

前端 未结 6 828
不思量自难忘°
不思量自难忘° 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-02 09:15

    In Mathematica you could do something like

    secretSanta[n_] := 
      DeleteCases[Permutations[Range[n]], a_ /; Count[a - Range[n], 0] > 0]
    

    where n is the number of people in the pool. Then for example secretSanta[4] returns

    {{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}}
    

    Edit

    It looks like the Combinatorica package in Mathematica actually has a Derangements function, so you could also do something like

    Needs["Combinatorica`"]
    Derangements[Range[n]]
    

    although on my system Derangements[Range[n]] is about a factor 2 slower than the function above.

提交回复
热议问题