Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I simulate a poker hand dealing in R?

Tags:

r

I play an online poker game, and I am concerned that the initial hands dealt to the player are not random after what seems to me after many observations too many non-random distributions. I'm trying to take 200-1000 hands dealt and compare it to a simulation to compare the distributions and see if it is indeed random. If it is, I would expect a uniform distribution. Anyways, I'm having a hard time figuring out how to store an array of 1,000 deals with two cards to each hand. Below is the code I have but every output prints out the same "2C and KC", 1000 times. Replace needs to equal false, since identical cards can't be dealt. I'd appreciate any help with solving this simulation, as well as any advice anyone may have as to going about this experiment. Thanks in advance!

cardDeck <- c("AH", "1H", "2H", "3H", "4H", "5H", "6H", "7H", "8H", "9H", "10H", "JH", "QH", "KH",
              "AS", "1S", "2S", "3S", "4S", "5S", "6S", "7S", "8S", "9S", "10S", "JS", "QS", "KS",
              "AC", "1C", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "10C", "JC", "QC", "KC",
              "AD", "1D", "2D", "3D", "4D", "5D", "6D", "7D", "8D", "9D", "10D", "JD", "QD", "KD")

deal <- function(cardDeck) {
  cardOne <- sample(cardDeck, 1, replace = FALSE)
  cardTwo <- sample(cardDeck, 1, replace = FALSE)
  handDealt <- paste(cardOne, cardTwo, sep = " and ")
}

cardsDealt <- rep(deal(cardDeck), 1000)
like image 445
Jason T. Eyerly Avatar asked Feb 11 '23 22:02

Jason T. Eyerly


2 Answers

Here are some improvements:

Generate deck compactly:

cardDeck <- c(outer(c("A",1:10,"J","Q","K"),
                    c("H","S","C","D"),
                    ## could use
                    ## "\u2661","\u2662","\u2667", "\u2664"
                  paste0))

As pointed out in comments, you need to choose all the cards in a hand in a single sample() call in order to get proper sampling without replacement (if you want to sample multiple hands from a single deal you need to modify this to sample all the cards from all the hands in a single sample() statement)

deal <- function(n=2,collapse=" and ") {
  paste(sample(cardDeck, n, replace=FALSE),
         collapse=collapse)
}

Use replicate() as suggested in comments and @ssdecontrol's answer:

set.seed(101)
replicate(5,deal())
## [1] "6S and 2H" "JC and 8C" "KH and 2S" "4C and 4S" "6C and 2C"  
like image 58
Ben Bolker Avatar answered Feb 14 '23 12:02

Ben Bolker


You want to use replicate, which will evaluate deal(cardDeck) 1000 times, instead of rep which will evaluate it once and then broadcast the result 1000 times. This is because the argument to replicate is an expression, whereas rep uses R's typical pass-by-value behavior, in that the arguments are evaluated before the function is called.

like image 35
shadowtalker Avatar answered Feb 14 '23 10:02

shadowtalker