r - 有效地从列表中创建配对的人,条件是他们以前从未配对过
问题描述
我有一个n
名字列表:sample = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
我还有一个不允许配对的配对列表,比如说sample2 = [['a', 'e'], ['e', 'g'], ['b', 'a']]
我想要一种随机创建对列表的有效方法sample
来获取列表,因为它们不存在于 中sample2
,例如:newlist = [['a', 'h'], ['b', 'g'], ['f', 'c'], ['e', 'd']]
。
每个元素需要在配对列表中出现一次,并且只出现一次。
我已经从这篇文章Efficiently pair random elements of list中看到了答案,这是在 Python 中完成的,并且没有 sample2 中的对不得出现的附加要求。
编辑 1:到目前为止,我所尝试的只是使用该函数并通过将列表切成两半sample()
来创建两组数据,然后我根据. 如果 sample2 中存在一对,它会再次使用该函数循环。我使用 26 进行迭代,但是名称列表和规则列表 ( ) 变得越来越大,导致运行时间更长。所以我想知道是否有更好、更有效的做事方式。randomised
sample2
sample()
sample2
代码块如下 - (注意name_data
是sample
上面的列表)
sumcheck <- rep(1, 26)
while (sum(sumcheck) > 0) {
randomised <- sample(name_data$ID)
setone <- randomised[1:(length(randomised)/2)]
settwo <- randomised[(length(randomised)/2 + 1) : length(randomised)]
matches <- data.frame(setone, settwo)
combination <- as.character(with(matches, interaction(setone,settwo)))
combinationreverse <- as.character(with(matches, interaction(settwo,setone)))
sumcheck <- (append(combination %in% sample2, combinationreverse %in% sample2))*1
}
解决方案
这会从符合条件的字母列表中生成随机匹配,然后过滤掉错误的组合。您可能希望通过仅保留不同的有效匹配并考虑禁止列表中的相反顺序来改进这一点。
set.seed(3)
people <- letters[1:4]
forbidden <- list(c('a', 'd'), c('a', 'b'), c('a', 'c'))
potentials <- lapply(1:5, function(x) c(sample(people, 1), sample(people, 1)))
matches <- potentials[!potentials %in% forbidden]
matches
[[1]]
[1] "d" "c"
[[2]]
[1] "d" "b"
[[3]]
[1] "d" "c"
[[4]]
[1] "c" "d"
推荐阅读
- html - 在Angular 8中提交成功后如何清除验证错误?
- flutter - 在屏幕底部移动 Stack 的子项
- javascript - div内滚动amchart图
- c# - 与 REST 客户端应用程序共享实体框架生成的模型的方法
- mysql - 将多个 MySQL 数据库推送到 ElasticSearch
- angular - Angular通过构造函数调用组件失败但可以在打字稿文件中正常导入
- automation - Isabelle 的自动求解器找不到正确的定理
- mongodb - Mongo $in 查询适用于独立的 mongo 实例,但不适用于 AWS DocumentDB 实例
- javascript - 我收到 java.security.cert.CertificateException:找不到名称匹配。Spring Boot 肥皂客户端
- wildfly - 为什么 Wildfly 会创建如此多的 Artemis 线程?