Secret Santa - Generating 'valid' permutations

前端 未结 6 886
不思量自难忘°
不思量自难忘° 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:26

    I propose this:

    f[s_List] := Pick[#, Inner[SameQ, #, s, Nor]] & @ Permutations@s
    
    f @ Range @ 4
    
    {{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}}

    This is significantly faster than Heike's function.

    f @ Range @ 9; //Timing
    secretSanta[9]; //Timing
    
    {0.483, Null}
    {1.482, Null}

    Ignoring transparency of code, this can be made several times faster still:

    f2[n_Integer] := With[{s = Range@n},
        # ~Extract~ 
           SparseArray[Times@@BitXor[s, #] & /@ #]["NonzeroPositions"] & @ Permutations@s
      ]
    
    f2[9]; //Timing
    
    {0.162, Null}

提交回复
热议问题