samedi 14 août 2021

Create sequence of binary values with a minimum run length

I want to create a random sequence of 0 or 1 of length 100. My only restriction is that the number must be at least in two consecutive periods:

Correct, all runs have at least two values:

1 1 0 0 0 1 1 1 0 0 0

Incorrect, some runs have less than two values:

1 0 0 1 0 1 1 1 0 1 1
      ^ ^       ^

This is my code, but is not working:

x <- NULL
x[1] <- sample(c(0, 1), replace = TRUE, size = 1)

for(i in 2:100){
  x[i] <- sample(c(0, 1), replace = TRUE, size = 1)
    
    
  x[i] <- if(x[i] + x[i-1] == 1){ 
            if(x[i-1] == 1){
                1
            } else {
        0
      }
    
  } else {
    sample(c(0, 1), replace = TRUE, size = 1)
  }
}
print(x)



Aucun commentaire:

Enregistrer un commentaire