Choose a random number, always with an increase in the value of the last random number selected

How could I effectively use a 1-to-1 upward random sampling of 1: n values, making sure that each of the random sampling values ​​is always higher than the previous value?

eg:.

For 1: 100 values, get a random number, say, which is 61. (current list = 61)
Then choose a different number from 62 to 100, let's say that is 90 (current list = 61.90)
Then choose a different number from 91 to 100, let's say that it is 100.
Stop the process when the maximum value has been hit (final list = 61.90,100)

I am stuck on the ground, thinking of this awkward:

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

I want to report a finite vector that is a concatenation of a1, a2, a (n):

 result <- c(a1,a2) 

Even if it sounds like a homework question, it is not. I gratefully left the days of homework many years ago.

+7
source share
5 answers

Late party, but I think this is going to rock your world:

 unique(cummax(sample.int(100))) 
+15
source

It uses a while and wraps it in a function

 # 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 

Edit

note the change you have to deal with when the new pattern is 100, and the sample method deals with an integer, not a vector for x

Edit 2

In fact, reading the help for sample gave a useful resample function. This avoids errors when length (x) == 1

+6
source

Not particularly effective, but:

 X <- 0 samps <- c() while (X < 100) { if(is.null(samps)) {z <- 1 } else {z <- 1 + samps[length(samps)]} if (z == 100) { samps <- c(samps, z) } else { samps <- c(samps, sample(z:100, 1)) } X <- samps[length(samps)] } 

samps EDIT: Trimming some fat from it:

 samps <- c() while (is.null(samps[length(samps)]) || samps[length(samps)] < 100 ) { if(is.null(samps)) {z <- 1 } else {z <- 1 + samps[length(samps)]} if (z == 100) { samps <- c(samps, z) } else { samps <- c(samps, sample(z:100, 1)) } } samps 
+3
source

later to the party, but only for kicks:

 X <- Y <- sample(100L) while(length(X <- Y) != length(Y <- X[c(TRUE, diff(X)>0)])) {} 

 > print(X) [1] 28 44 60 98 100 
+1
source

Sort random vectors

Create a vector of random integers and sort it afterwards.

 sort(sample(1:1000, size = 10, replace = FALSE),decreasing = FALSE) 

It gives 10 random integers from 1 to 1000.

 > sort(sample(1:1000, size = 10, replace = FALSE),decreasing = FALSE) [1] 44 88 164 314 617 814 845 917 944 995 

This of course also works with random decimal places and floats.

0
source

All Articles