Skip to content

Instantly share code, notes, and snippets.

@MarkBennett
Created December 8, 2013 18:54
Show Gist options
  • Save MarkBennett/7862147 to your computer and use it in GitHub Desktop.
Save MarkBennett/7862147 to your computer and use it in GitHub Desktop.
My solution to the first Dart Dare (https://plus.google.com/u/0/+SethLadd/posts/XjgFRvqtVA4)
import 'dart:math';
void main() {
List<String> names = '''
Zoe Washburne
Hoban Washburne
Malcolm Reynolds
Simon Tam
River Tam
Buffy Summers
Dawn Summers'''.split("\n");
last_names_match(pair) {
var last_names = pair.map((name) => name.split(" ").last);
return last_names.first == last_names.last;
}
names_match(pair) {
return pair.first == pair.last;
}
candidate_matches_pick(pick, candidate) {
return pick != null && (pick.first == candidate.first || pick.last == candidate.last);
}
can_swap_pick_with_name(pick, name, missing_name) {
return pick.last != name && pick.first.split(" ").last != name.split(" ").last && pick.first != missing_name && pick.first.split(" ").last != missing_name.split(" ").last;
}
pick_names(List names) {
var random = new Random();
List candidates = names.map((name) => names.map((n) => [name, n])).expand((i) => i).toList()..removeWhere(names_match)..removeWhere(last_names_match);
candidates.shuffle(random);
List<List> picks = names.map((name) {
var pick = candidates.firstWhere((candidate) => candidate.first == name, orElse: () => [name, null]);
candidates.removeWhere((candidate) => candidate_matches_pick(pick, candidate));
return pick;
}).toList();
// Handle the case where the last person ran out of picks
// This happens if the only name left was themselves, or if the remaining name was excluded because of their last name
if (picks.last.last == null) {
var bad_pick = picks.last;
var missing_name = names.toSet().difference(picks.map((pick) => pick.last).toSet()).first;
var swappable_pick = picks.firstWhere((pick) => can_swap_pick_with_name(pick, bad_pick.first, missing_name));
bad_pick[1] = swappable_pick.last;
swappable_pick[1] = missing_name;
}
return picks;
}
var picks = pick_names(names);
picks.forEach((pick) {
print("${pick.first} is buying a gift for ${pick.last}.");
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment