Search code examples
rprobability

Assuming a 5 card poker hand what is the probability of having four of a kind? Use R


I know the basic hand calculation is

comb_wo = function(n, x) {
   factorial(n) / factorial(n-x) / factorial(x)
}  
d <- comb_wo(13,1)*comb_wo(4,4)*comb_wo(48,1)/comb_wo(52,5)
d  

but if I want to simulation 100 times, and then find out the probability?


Solution

  • You will have to create a deck of cards, e.g.

    Value <- rep(c(2:10, "Jack", "Queen", "King", "Ace"), each=4)
    Suit <- rep(c("Clubs", "Diamonds", "Hearts", "Spades"), 13)
    Deck <- data.frame(Suit, Value)
    

    Then to create a random hand of 5:

    Hand <- Deck[sample.int(52, 5), ]
    

    Do this many times, (100 will not be enough):

    set.seed(42) # Just to make this illustration reproducible
    Hands <- replicate(10000, Deck[sample.int(52, 5), ], simplify=FALSE)
    

    How many have a four of a kind:

    fourkind <- sapply(seq(10000), function(x) any(table(Hands[[x]]$Value) == 4))
    sum(fourkind)
    #  [1] 1
    idx <- which(fourkind)
    idx
    # [1] 983
    

    If you have a hand(s) with four of a kind:

    lapply(idx, function(i) Hands[[i]])
    # [[1]]
    #        Suit Value
    # 10 Diamonds     4
    # 12   Spades     4
    # 9     Clubs     4
    # 41    Clubs Queen
    # 11   Hearts     4