How to simulate a poker hand in R?

I play an online poker game and it worries me that the initial hands dealt to a player are not random after what seems to me after many observing too many non-random distributions. I'm trying to take 200-1000 hands out and compare them to a simulation to compare distributions and see if it's really random. If so, then I would expect an even distribution. Anyway, I'm having a hard time figuring out how to store an array of 1000 trades with two cards in each hand. Below is the code I have, but each output outputs the same "2C and KC" 1000 times. Replace with false, since identical cards cannot be processed. I would appreciate any help with this simulation, as well as any advice you might have regarding 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)

      

+3


source to share


2 answers


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 replicate

is expression

, while it rep

uses the typical behavior of R with respect to R, since the arguments are evaluated before the function is called.



+3


source


Here are some improvements:

Deck building is compact:

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 the comments, you need to select all the cards in your hand in one call sample()

to get the correct selection without swapping (if you want to select multiple hands from one trade you need to change this to select all cards from all hands in one expression sample()

)



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

      

Use replicate()

as pointed out in comments and @ sdecontrol's answer:

set.seed(101)
replicate(5,deal())
## [1] "6S and 2H" "JC and 8C" "KH and 2S" "4C and 4S" "6C and 2C"  

      

+5


source







All Articles