31 ms·
Show HN: Secret Santa in python
- api_or_ipa 9y agoThis 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!
- lazy_guy 9y agoMy implementation: def santa_list(people): return dict(zip( people[1:] + people[:1], people)) (shuffle if you want to).
- api_or_ipa 9y agoThat's brilliantly simple. I really need to use `zip` more often in my python code. Thanks for sharing your succinct solution.
- Bahamut 9y agoI created one in JS a couple of years back for fun (not as clean as I’d like, but I did it in an hour or two of work: https://github.com/wesleycho/secret-santa https://github.com/wesleycho/secret-santa It’s a surprisingly fun little problem
- josefelix 9y agoAwesome script! Will give it a try next year.