如何在R中生成随机整数,以使两个连续的数字都不相同 [英] How to generate random integers in R so that no two consecutive numbers are the same

查看:660
本文介绍了如何在R中生成随机整数,以使两个连续的数字都不相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a method to generate random integers in R such that any two consecutive numbers are different? It is probably along the lines of x[k+1] != x[k] but I can't work out how to put it all together.

推荐答案

不确定是否有可用的功能.也许此功能可以完成您想做的事情:

Not sure if there is a function available for that. Maybe this function can do what you want:

# 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

希望这会有所帮助.

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

The function above has a long worst-case runtime. We can keep that worst-case more constant with for example the following implementation:

# 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)
}

这篇关于如何在R中生成随机整数,以使两个连续的数字都不相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆