Secret Santa - Generating 'valid' permutations

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

    What you're looking for is called a derangement (another lovely Latinate word to know, like exsanguination and defenestration).

    The fraction of all permutations which are derangements approaches 1/e = approx 36.8% -- so if you are generating random permutations, just keep generating them, and there's a very high probability that you'll find one within 5 or 10 selections of a random permutation. (10.1% chance of not finding one within 5 random permutations, every additional 5 permutations lowers the chance of not finding a derangement by another factor of 10)

    This presentation is pretty down-to-earth and gives a recursive algorithm for generating derangements directly, rather than having to reject permutations that aren't derangements.

提交回复
热议问题