Simple derangement algorithm (secret santa)

492 Views Asked by At

In combinatorial mathematics, a derangement is a permutation of the elements of a set, such that no element appears in its original position. - from Wikipedia

A real example might be a secret santa draw where each person is randomly assigned another person who they have to buy a present, and everyone should be assigned only once to someone (but not themselves).

Anyway, I saw a lot of algorithms that just try random combinations until no "collisions" occur. My question is can we use a trivial solution where we map each element to the next, and the last one to the first: $$(a_1, a_2,...a_n) \implies (a_2, a_3, ..., a_n, a_1) $$ However, my idea is to first shuffle the elements or take a permutation, and then map them as previously explained.

Example:

  1. Take ANY permutation, collisions 3 and 4 are fine

$$ (1, 2, 3, 4) \implies (2, 1, 3, 4) $$

  1. And then we apply the "trivial" mapping:

$$ (2, 1, 3, 4) \implies (1, 3, 4, 2) $$

  1. Reverse shuffle to finally get:

$$ (1, 2, 3, 4) \implies (3, 1, 4, 2) $$

Wouldn't this work faster then just "guessing", since we take any random permutation without discarding it? Is there any bias?