Intro to R and a Gambling Demo

I gave a 50-minute presentation at SUNY Fredonia’s Spring 2016 Faculty Professional Development Day. It was a very nice experience. Of course, I prepared way more content than was reasonable for a 50-minute presentation, but I think it went well, anyway. Here is the presentation (PowerPoint; I know all the cool R people use LaTeX for their R presentation slides, but… ).

One thing I did not do in the presentation was a demo I created for simulating 100,000 games of Twenty-One against a dealer, when you have a “hold rule” of 18 or higher, and the dealer has a rule of 17 or higher. It’s over-simplified: Aces always count as 1, and there are only two card draws after the initial deal. However, I think it is at least a little bit fun.

At some point I should go back and add the possibility of Aces being 1 or 11, and also make the output at each step pretty. But for an intro workshop this seemed appropriate, if too long-winded for a 50-minute session. The code is after the break.

# Demo: twenty-one -----------------------------------------
# Generate some card values (1=Ace, extra 10's for J, Q, K)
cvals <- c(1:10, 10, 10, 10)
# First card: sample from those values, 100,000 times.
card1 <- sample(cvals, 100000, replace=TRUE)
# Second card: sample again
card2 <- sample(cvals, 100000, replace=TRUE)
# add card1 and card2
sum2 <- card1 + card2
# third card
card3 <- sample(cvals, 100000, replace=TRUE)
# go back and change third card to zero if sum of first two cards is > hold rule
card3[sum2 > 18] <- 0
# now sum up cards 1:3 (zeroes don't count, so it's as if they weren't dealt)
sum3 <- sum2 + card3
# fourth card and setting value to zero if previous sum > hold rule
card4 <- sample(cvals, 100000, replace=TRUE)
card4[sum3 > 18] <- 0
# sum of 4 cards; we'll stop here.
sum4 <- sum3 + card4
# Now the dealer's cards...
# cards 1 & 2, then sum
card1.d <- sample(cvals, 100000, replace=TRUE)
card2.d <- sample(cvals, 100000, replace=TRUE)
sum2.d <- card1.d + card2.d
# card 3 and set value to 0 if sum2 > hold value
card3.d <- sample(cvals, 100000, replace=TRUE)
card3.d[sum2.d > 17] <- 0
# sum of 3 cards
sum3.d <- sum2.d + card3.d
# card 4 and set value to 0 if sum3 > hold value
card4.d <- sample(cvals, 100000, replace=TRUE)
card4.d[sum3.d > 17] <- 0
# sum of 4 cards
sum4.d <- sum3.d + card4.d
# histograms: Just to see the result (and the weird distribution)
par(mfrow=c(2,1))
hist(sum4, col="lightgreen")
abline(v=21, col="red", lwd=3)
hist(sum4.d, col="pink")
abline(v=21, col="red", lwd=3)
# wins
wins <- sum4 > sum4.d & sum4 <= 21
table(wins)
prop.table(table(wins))

Leave a Reply

Your email address will not be published. Required fields are marked *