[R] Head or Tails game

darnold dwarnold45 at suddenlink.net
Sat Aug 4 02:55:17 CEST 2012


Hi,

Reading about a "Heads and Tails" game in 
http://www.dartmouth.edu/~chance/teaching_aids/books_articles/probability_book/amsbook.mac.pdf
Introduction to Probability  (Example 1.4, pp. 5-8).

You toss a coin 40 times. If heads, Peter wins $1, tails, he loses $1. I
think I can do that ok with:

winnings <- sum(sample(c(-1,1), 40, replace=TRUE))

But I have to do it 10,000 times and I have to record and collect the
winnings. In other languages, I would probably use a for loop and "push"
each winnings into some sort of collective array or vector. However, for
loops seem to be discouraged in R and it seems the same can be said for
"pushing" a calculation onto a vector. So, can someone give me some guidance
on how to collect 10,000 winnings?

The second part of the game asks us to keep track of how often Peter is in
the lead during each game. Obviously, he is in the lead at any moment his
cumulative winnings are positive. But the game requires that we also do
something at the moment the cumulative winnings are zero. (1) if the
previous cumulative sum was nonnegative, then the zero counts a "staying in
the lead." So, for example, during a single game, Peter might be in the lead
for say 34 out of the 40 tosses. I must record the 34 and perform the game
9,999 more times, each time recording the number of times that Peter is in
the lead. So again, any thoughts on how to do  this without for loops and
"pushing?"

Thanks for the help. Great list.

David Arnold
College of the Redwoods
Eureka, CA
http://msemac.redwoods.edu/~darnold/index.php



--
View this message in context: http://r.789695.n4.nabble.com/Head-or-Tails-game-tp4639142.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list