我正在尝试模拟一个对我们年度秘密圣诞老人有限制的排序帽。
该计划应随机分配与去年作业不重叠的礼品赠送者。
我试图将所有内容放在while
循环中。但是,我不认为约束是有效的。
这是我到目前为止所做的:
# set up data
rm(list = ls())
names <- c('sally', 'linus', 'lucy', 'snoopy', 'peppermint', 'pigpen')
# hard code the past
past <- c("lucy", "pigpen", "peppermint", "sally", "snoopy", "linus")
df <- data.frame("names" = names, "past" = past)
# sorting hat
hat <- function(x) {
success <- FALSE
while (!success) {
# pick name from hat
pick <- sample(names, replace = F)
# create T/F vectors to see if any picks are same as self or past
# then bind them into object so the success test returns a single T/F value
check_name <- c(pick == names)
check_past <- c(pick == past)
check = cbind(check_name, check_past)
# success = T if any elements of test are TRUE
success <- TRUE %in% check
}
x$pick = pick
return(x)
}
> hat(df)
names past pick
1 sally lucy pigpen
2 linus pigpen linus
3 lucy peppermint peppermint
4 snoopy sally sally
5 peppermint snoopy snoopy
6 pigpen linus lucy
有什么想法?
答案 0 :(得分:2)
您的功能几乎没问题,您应该只有success <- TRUE %in% check
而不是set.seed(2015)
hat <- function(x) {
pick <- sample(x$names, replace = FALSE)
while(any(x$past == pick | x$names == pick))
pick <- sample(x$names, replace = FALSE)
x$pick <- pick
x
}
。更短的东西:
mouseDownPosition: Signal (Int, Int)
mouseDownPosition =
Signal.map2 (,) Mouse.position Mouse.isDown
|> Signal.filter snd ((0, 0), False)
|> Signal.map fst