首页 > 解决方案 > 有效地从列表中创建配对的人,条件是他们以前从未配对过

问题描述

我有一个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 进行迭代,但是名称列表和规则列表 ( ) 变得越来越大,导致运行时间更长。所以我想知道是否有更好、更有效的做事方式。randomisedsample2sample()sample2

代码块如下 - (注意name_datasample上面的列表)

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
}

标签: rlistcombinations

解决方案


这会从符合条件的字母列表中生成随机匹配,然后过滤掉错误的组合。您可能希望通过仅保留不同的有效匹配并考虑禁止列表中的相反顺序来改进这一点。

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"

推荐阅读