选择一个随机数,总是随着上次随机数的增加而增加

the*_*ail 7 random r sample

我将如何有效地采用值1:n的1乘1递增随机样本,确保每个随机采样值始终高于先前值?

例如:

对于值1:100,得到一个随机数,比如哪个是61.(当前列表= 61)
然后选择62和100之间的另一个数字,比如哪个是90(当前列表= 61,90)
然后在91之间选择另一个数字和100,说哪个是100.
在最大值被击中时停止进程(最终列表= 61,90,100)

我被困在循环的土地上,以这种笨重的方式思考:

a1 <- sample(1:100,1)

if(a1 < 100) {
    a2 <- sample((a+1):100,1)
        }

etc etc...
Run Code Online (Sandbox Code Playgroud)

我想报告最终的向量是a1,a2,a(n)的串联:

result <- c(a1,a2)
Run Code Online (Sandbox Code Playgroud)

即使这听起来像是一个家庭作业问题,但事实并非如此.我很幸运地离开了很多年前的家庭作业.

flo*_*del 16

晚会很晚,但我认为这会震撼你的世界:

unique(cummax(sample.int(100)))
Run Code Online (Sandbox Code Playgroud)


mne*_*nel 6

这使用while循环并包含在函数中

# from ?sample
resample <- function(x, ...) x[sample.int(length(x), ...)]

sample_z <-  function(n){
  z <- numeric(n)
  new <- 0
  count <- 1

  while(new < n){
    from <- seq(new+1,n,by=1)
    new <- resample(from, size= 1)
    z[count] <- new
    if(new < n)  count <- count+1
  }

  z[1:count]
}

set.seed(1234)

sample_z(100)
## [1]  12  67  88  96 100
Run Code Online (Sandbox Code Playgroud)

编辑

注意当新样本为100时处理的变化以及处理sample整数而不是向量的方式x

编辑2

实际上阅读帮助sample给了有用的resample功能.当长度(x)== 1时,这避免了陷阱