vendredi 9 juillet 2021

Random number generation in R without a contiguous repeat

I want to test the useful life of two parts where one (part A) moves within the other (part B). There are 10 possible distinct "destinations" for Part A to land. Useful life is defined as 15,000 movements.

I've tried to generate a vector of "destinations" and eliminate having the same "destination" appear back-to-back. I can generate the vector but cannot figure out how to eliminate a back-to-back repeat. With acceptable output I can program a motor to step through each "destination" until useful life and test other mechanical attributes of both parts.

Here's my code:


    iterations <- (50) ##just to test the code

    LSVmin <- (1)
    LSVmax <-(10)

    movementV <- matrix(data=0, nrow=iterations, ncol=1) ##create vector for movement values 

    movementV[1,] <- 10

    i <- 2
    for (i in 2:iterations) {

        movement1 <- (floor(runif(1, min=LSVmin, max=LSVmax)))
        movementV[i, ] <- movement1
   
        if (identical(movementV[i, ], movementV[i-1, ]) > 0) 

                movementV[i, ] <- movement1
   
        else  {

                movement2 <- (floor(runif(1, min=LSVmin, max=LSVmax))) ##no provision for repeats 
                movementV[i, ] <- movement2
              }
    i<- (i + 1)  ### iterate the loop
     }

I've tried a number of methods to compare subsequent values but I don't know how to establish a variable within the if...else routine and not lose it when the loop iterates.




Aucun commentaire:

Enregistrer un commentaire