[R] Head or Tails game

Nordlund, Dan (DSHS/RDA) NordlDJ at dshs.wa.gov
Mon Aug 6 08:20:44 CEST 2012


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of darnold
> Sent: Friday, August 03, 2012 9:18 PM
> To: r-help at r-project.org
> Subject: Re: [R] Head or Tails game
> 
> Wow! Some great responses!
> 
> I am getting some great responses. I've only read David, Michael, and
> Dennis
> thus far, leading me to develop this result before reading further.
> 
> lead <- function(x) {
>   n <- length(x)
>   count <- 0
>   if (x[1] >= 0) count <- count + 1
>   for (i in 2:n) {
>     if (x[i] > 0 || (x[i] == 0 && x[i-1] >= 0 )) {
>       count  <- count + 1
>     }
>   }
>   count
> }
> 
> games <- replicate(10000,sample(c(-1,1),40,replace=TRUE))
> 
> games_sum <- apply(games,2,sum)
> plot(table(games_sum))
> 
> games_lead <- apply(games,2,cumsum)
> games_lead <- apply(games_lead,2,lead)
> plot(table(games_lead))
> 
> Now I am going to read Arun, William, and Jeff's responses and see what
> other ideas are being proposed.
> 
> Thanks everyone.
> 
> D.
> 


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




More information about the R-help mailing list