更换样品,避免重复

时间:2017-03-07 15:46:06

标签: r

我正在编写一个游戏,其中包括执行一个函数,该函数从列表中选择一个随机的人并从其他列表中选择一个随机的主题。

主要规则是: - 您可以随时运行代码,但代码不能提供相同人的2倍

目前我得到的是:

# Lists 
people = list('john','peter','alex')
topic = list('Finance','Ensurance','Retail')

Start<-function(people, topic){
  arg1 = sample(people,1)
  arg2 = sample(topic,1)
  return (list(arg1,arg2))
}

问题的关键在于:确保每次运行“开始”功能时,人物p和p + 1都不相同。所以,结果可能是:

John,Finance / peter,Finance / John,Retail / alex,Finance 但从来没有:John,Finance / John,Finance。

1 个答案:

答案 0 :(得分:3)

我可能会制作一个生成样式函数

people <- c('john','peter','alex')
topic <- c('Finance','Ensurance','Retail')

Starter <- function(people, topic){
  last.person <- ""
  function() {
     next.person <- sample(setdiff(people, last.person), 1)
     next.topic <- sample(topic,1)
     last.person <<- next.person
     return(list(next.person, next.topic))
  }
}

s <- Starter(people, topic)
s()
s()
s()

此处Starter()返回一个可以调用以获取新样本的函数。它跟踪最后选择的人并将其从可能的抽奖列表中排除。请注意,我使用简单向量作为选项列表而不是列表,以使事情变得更容易。

相关问题