Created
December 2, 2016 00:58
-
-
Save njtierney/d322537cea9c4732ef3cb52a86fb2677 to your computer and use it in GitHub Desktop.
Generate secret santa lists
This file contains hidden or 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 is taken from Amy Whitehead's great blog: https://amywhiteheadresearch.wordpress.com/2016/12/01/santas-little-helper/ | |
SantasLittleHelper <- function(myFrame,guestList,conflictCols = NULL){ | |
myTest <- TRUE | |
nElves <- 0 | |
while (myTest == TRUE){ | |
myOut <- data.frame(gifter = myFrame[,guestList], | |
giftee = sample(myFrame[,guestList], | |
replace = FALSE, | |
size=nrow(myFrame)) | |
) | |
# check that guests haven't drawn themselves | |
guestTest<- unlist(lapply(1:nrow(myOut),function(x) { | |
myOut$giftee[x] == myFrame[x,guestList] | |
})) | |
# check for gifting conflicts | |
if(!is.null(conflictCols)){ | |
conflictTest <- unlist(lapply(1:nrow(myOut),function(x) { | |
grepl(myOut$giftee[x],myFrame[x,conflictCols]) | |
})) | |
myTest <- any(c(guestTest,conflictTest[!is.na(conflictTest)])) | |
} else{ | |
myTest <- any(guestTest) | |
} | |
# count the number of iterations needed to avoid conflicts | |
nElves <- nElves + 1 | |
} | |
message(paste(nElves,"elves were needed to generate the gift list")) | |
return(myOut) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment