Skip to content
Prev 302432 / 398506 Next

Head or Tails game

Here is another solution that doesn't need to define an additional function with an explicit loop. It seems to be considerably faster than the approach presented above.

system.time({
  set.seed(123)
  games <- matrix(sample(c(-1, 1), 40*10000, TRUE), ncol = 10000)
  games_sum <- apply(games,2,cumsum)
  games_lead <- colSums((games_sum > 0) | (games_sum==0 & games==-1))
})
   user  system elapsed 
   0.08    0.00    0.08 

plot(table(games_sum[40,]))
plot(table(games_lead))


Compare this with your solution

system.time({
set.seed(123)
games <- replicate(10000,sample(c(-1,1),40,replace=TRUE))

games_sum <- apply(games,2,sum)

games_lead <- apply(games,2,cumsum)
games_lead <- apply(games_lead,2,lead)
})
   user  system elapsed 
   0.95    0.02    0.98 


Hope this is helpful,

Dan

Daniel J. Nordlund
Washington State Department of Social and Health Services
Planning, Performance, and Accountability
Research and Data Analysis Division
Olympia, WA 98504-5204