Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using R as a game simulator

I am trying to simulate a simple game where you spin a spinner, labeled 1-5, and then progress on until you pass the finish line (spot 50). I am a bit new to R and have been working on this for a while searching for answers. When I run the code below, it doesn't add the numbers in sequence, it returns a list of my 50 random spins and their value. How do I get this to add the spins on top of each other, then stop once => 50?

SpacesOnSpinner<-(seq(1,5,by=1))
N<-50
L1<-integer(N)

for (i in 1:N){
takeaspin<-sample(SpacesOnSpinner,1,replace=TRUE)
L1[i]<-L1[i]+takeaspin
} 
like image 530
user2187731 Avatar asked Jan 14 '23 12:01

user2187731


1 Answers

This is a good use-case for replicate. I'm not sure if you have to use a for loop, but you could do this instead (replicate is a loop too):

SpacesOnSpinner<-(seq(1,5,by=1))
N<-10
cumsum( replicate( N , sample(SpacesOnSpinner,1,replace=TRUE) ) )
#[1]  5 10 14 19 22 25 27 29 30 33

However, since you have a condition which you want to break on, perhaps the other answer with a while condition is exactly what you need in this case (people will tell you they are bad in R, but they have their uses). Using this method, you can see how many spins it took you to get past 50 by a simple subset afterwards (but you will not know in advance how many spins it will take, but at most it will be 50!):

N<-50
x <- cumsum( replicate( N , sample(5,1) ) )

# Value of accumulator at each round until <= 50
x[ x < 50 ]
#[1]  5  6  7  8 12 16 21 24 25 29 33 34 36 38 39 41 42 44 45 49

# Number of spins before total <= 50
length(x[x < 50])
[1] 20
like image 53
Simon O'Hanlon Avatar answered Jan 16 '23 19:01

Simon O'Hanlon