This year my friend group is using Elfster to distribute secret santa names. This got me thinking about how to write a good implementation of the secret santa "elf". The problem has some interesting properties: a good algorithm should never assign a person to give a gift to him/herself. I extended that property to say that no pair of people should send/rec'v from each other. Extending this out, we might even say a good secret santa will ensure there are no partitions in the group: following the linked list of senders, you should iterate over everyone in the group.
Viewed like that, an "optimal" solution is brilliantly simple: given n names, shuffle the array of names, then assign person[k] to give to person[k+1], with the special case where k == n, person[k] gives to person[0].
The rest of the short implementation adds a `receive_from` property to each person which could be useful in QAing the implementation.
If you still need to assign Secret Santa givers, feel free to use my implementation!
5 comments
[ 4.8 ms ] story [ 25.9 ms ] threadViewed like that, an "optimal" solution is brilliantly simple: given n names, shuffle the array of names, then assign person[k] to give to person[k+1], with the special case where k == n, person[k] gives to person[0].
The rest of the short implementation adds a `receive_from` property to each person which could be useful in QAing the implementation.
If you still need to assign Secret Santa givers, feel free to use my implementation!
It’s a surprisingly fun little problem