How to solve the Secret Santa Problem using graph theory
medium.com
medium.com
In other news, at this past Secret Santa I got a desk-mounted boom for my Blue Yeti, which I use every day and am thankful for.
import random
l = ['Alice', 'Bob', 'Benny', 'Dolores']
random.shuffle(l)
r = dict(zip(l, (l[(i + 1) % len(l)] for i in range(0, len(l)))))
print(r)
Basically just shuffle the list, assign everybody the one next on the list (with wrap around).I have a feeling that this is not correct, but cannot determine why.
This constrains the problem less but I don't think it allows a simpler algorithm. Your approach still needs some backtracking, if I understand right: what if Alice and Bob are the last two to be picked?
The tradition says that after opening the gift they've received, they have to wear the funny Santa hat and bring the gift they brought to the person they were randomly assigned.
If the graph is not Hamiltonian, and instead goes A-B-C-A and D-E-F-D and G-H-G, there are going to be several awkward moments where someone has to arbitrarily choose someone who hasn't gone yet. It's really easy to generate these loops, and hard to get a 'proper' graph by drawing randomly from a hat, especially if you add other constraints like excluding spouses and your own kids/parents.