【问题标题】:How to generate random integers in R so that no two consecutive numbers are the same如何在R中生成随机整数,以便没有两个连续的数字相同
【发布时间】:2018-06-16 03:19:21
【问题描述】:

有没有一种方法可以在 R 中生成随机整数,使得任何两个连续数字都不同?它可能与x[k+1] != x[k] 类似,但我不知道如何将它们组合在一起。

【问题讨论】:

  • 您是从一组固定的整数中生成的吗?您可以直接取样而不更换吗?

标签: r random integer sequence


【解决方案1】:

另一种方法是过采样并删除不合格的,如下所示:

# assumptions
n <- 5               # population size
sample_size <- 1000


# answer
mu <- sample_size * 1/n
vr <- sample_size * 1/n * (1 - 1/n)
addl_draws <- round(mu + vr, 0)


index <- seq(1:n)
sample_index <- sample(index, sample_size + addl_draws, replace = TRUE)


qualified_sample_index <- sample_index[which(diff(sample_index) != 0)]
qualified_sample_index <- qualified_sample_index[1:sample_size]

# In the very unlikely event the number of qualified samples < sample size,
# NA's will fill the vector.  This will print those N/A's
print(which(is.na(qualified_sample_index) == TRUE))

【讨论】:

    【解决方案2】:

    不确定是否有可用的功能。也许这个功能可以做你想做的事:

    # n = number of elements
    # sample_from = draw random numbers from this range
    random_non_consecutive <- function(n=10,sample_from = seq(1,5))
    {
      y=c()
      while(length(y)!=n)
      {
        y= c(y,sample(sample_from,n-length(y),replace=T))
        y=y[!c(FALSE, diff(y) == 0)]
      }
      return(y)
    }
    

    例子:

    random_non_consecutive(20,c(2,4,6,8))
    [1] 6 4 6 2 6 4 2 8 4 2 6 2 8 2 8 2 8 4 8 6
    

    希望这会有所帮助。


    上面的函数有很长的最坏情况运行时间。例如,我们可以通过以下实现使最坏情况保持不变:

    # n = number of elements
    # sample_from = draw random numbers from this range
    random_non_consecutive <- function(n=10,sample_from = seq(1,5))
    {
      y= rep(NA, n)
      prev=-1 # change this if -1 is in your range, to e.g. max(sample_from)+1
      for(i in seq(n)){
        y[i]=sample(setdiff(sample_from,prev),1)
        prev = y[i]
      }
      return(y)
    }
    

    【讨论】:

    • 两个选项:将第一个函数与数字一起使用,然后将其与您的字符向量进行匹配,例如:letters[random_non_consecutive(10,seq(letters))]。第二种选择:使用我后来添加的函数random_non_consecutive(10,letters)。让我知道这是否能解决您的问题
    • 'sample' 函数包含一个 prob 参数。因此,您必须使用和修改我提供的第二个函数,方法是在基于 prev 的示例函数中添加正确的概率。希望有帮助
    • 我建议您将其作为一个单独的问题发布,并解释您在那里寻找的确切行为。这对于评论部分来说有点长;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    • 2021-11-12
    • 1970-01-01
    相关资源
    最近更新 更多