-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implement secret santa with backtracking
Prevent flaky failures from invalid combinations.
- Loading branch information
Showing
3 changed files
with
54 additions
and
42 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
import random | ||
|
||
|
||
def _is_valid_assignment(source, target, exclusions): | ||
if source == target: | ||
return False | ||
if (source, target) in exclusions: | ||
return False | ||
return True | ||
|
||
|
||
def _backtrack_assignments(participants, exclusions, assignments, targets): | ||
if not participants: | ||
return assignments | ||
|
||
source = participants[0] | ||
random.shuffle(targets) # Shuffle targets to ensure randomness | ||
for target in targets: | ||
if _is_valid_assignment(source, target, exclusions): | ||
new_assignments = assignments + [(source, target)] | ||
new_targets = targets[:] | ||
new_targets.remove(target) | ||
result = _backtrack_assignments( | ||
participants[1:], exclusions, new_assignments, new_targets | ||
) | ||
if result: | ||
return result | ||
|
||
return None | ||
|
||
|
||
def resolve_secret_santa( | ||
participants, | ||
exclusions, | ||
): | ||
return _backtrack_assignments(participants, exclusions, [], participants[:]) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
[tool.isort] | ||
line_length = 88 |