Secret santa algorithm

前端 未结 9 1423
温柔的废话
温柔的废话 2020-12-04 22:26

Every Christmas we draw names for gift exchanges in my family. This usually involves mulitple redraws until no one has pulled their spouse. So this year I coded up my own

9条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-04 22:36

    I just created a web app that will do exactly this - http://www.secretsantaswap.com/

    My algorithm allows for subgroups. It's not pretty, but it works.

    Operates as follows:
    1. assign a unique identifier to all participants, remember which subgroup they're in
    2. duplicate and shuffle that list (the targets)
    3. create an array of the number of participants in each subgroup
    4. duplicate array from [3] for targets
    5. create a new array to hold the final matches
    6. iterate through participants assigning the first target that doesn't match any of the following criteria:
         A. participant == target
         B. participant.Subgroup == target.Subgroup
         C. choosing the target will cause a subgroup to fail in the future (e.g. subgroup 1 must always have at least as many non-subgroup 1 targets remaining as participants subgroup 1 participants remaining)
         D. participant(n+1) == target (n +1)
    If we assign the target we also decrement the arrays from 3 and 4

    So, not pretty (at all) but it works. Hope it helps,

    Dan Carlson

提交回复
热议问题