[R] Head or Tails game

arun smartpink111 at yahoo.com
Sat Aug 4 06:20:44 CEST 2012



Hi,

system.time({
set.seed(111)
colSums(matrix(sample(c(-1, 1), 40*10000, TRUE), ncol = 10000))
})
user  system elapsed 
  0.032   0.012   0.041 

system.time({
 set.seed(112)
 list1<-vector("list",10000)
 for(i in 1:10000){
  list1[[i]]<-sample(c(-1,1),40,replace=TRUE)}
  dat1<-do.call(rbind,lapply(list1,function(x) sum(x)))
 dat2<-matrix(dat1,ncol=200,byrow=TRUE)
 })
   user  system elapsed 
  0.112   0.000   0.111 
#modified version

system.time({
 set.seed(112)
 list1<-vector("list",10000)
 for(i in 1:10000){
  list1[[i]]<-sample(c(-1,1),40,replace=TRUE)}
  dat1<-unlist(lapply(list1,function(x) sum(x)))
  })
 user  system elapsed 
 0.092   0.000   0.092 


It seems like Michael's solution is better in terms of the CPU utilization.  I guess, the loop created the difference.

A.K.



----- Original Message -----
From: Michael Weylandt <michael.weylandt at gmail.com>
To: darnold <dwarnold45 at suddenlink.net>
Cc: "r-help at r-project.org" <r-help at r-project.org>
Sent: Friday, August 3, 2012 10:20 PM
Subject: Re: [R] Head or Tails game



On Aug 3, 2012, at 9:14 PM, darnold <dwarnold45 at suddenlink.net> wrote:

> David,
> 
> set.seed(123)  # always good to make reproducible 
> winnings <- sum(sample(c(-1,1), 10000, replace=TRUE)) 
> 
> Unfortunately, that's not the game. The game requires 40 flips of a coin.
> 
> Then you have to play the game 10,000 times.
> 

colSums(matrix(sample(c(-1, 1), 40*10000, TRUE), ncol = 10000))

or some such

Michael

> D.
> 
> 
> 
> --
> View this message in context: http://r.789695.n4.nabble.com/Head-or-Tails-game-tp4639142p4639145.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list