如何在R中生成随机整数,以便没有两个连续的数字相同

时间:2018-01-06 14:33:34

标签: r random integer sequence

是否有一种在R中生成随机整数的方法,使得任何两个连续的数字都不同?它可能与x[k+1] != x[k]一致,但我无法弄清楚如何将它们放在一起。

2 个答案:

答案 0 :(得分: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)
}

答案 1 :(得分: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))