Home > Back-end >  How do I simulate choosing a random player at first, and then repeating that sequence?
How do I simulate choosing a random player at first, and then repeating that sequence?

Time:11-13

I am trying to simulate a game in R. For that I need to choose a random player out of n_players who begins in the first round. Then the other n_players follow in a random order in the first round. However, in the next rounds the same order of players as in the first round must be kept. Does anyone have an idea on how to do this?

CodePudding user response:

Create a sequence of numbers, say n=10, from 1 up to n.

x<-1:10

Think of this to be the tag number of players. You can then use the sample function of R (read the documentation using ?sample command or visit here) to create another sequence of numbers whose order have been shuffled randomly.

y<-sample(x,10,replace=F)

Now your y variable is the order in which your players are selected one by one.

Also, you can access each individual chosen player just like you choose an element from a vector.

Finally, the vector y is the sequence in which these players are selected in the subsequent rounds.

Test run:

x<-1:10
#[1]  1  2  3  4  5  6  7  8  9 10

y<-sample(x,10,replace=F)
#[1]  2  4  1  8  9  7  5  6 10  3
  •  Tags:  
  • r
  • Related