Search code examples
rprobability

Simulate the probability to get four-of-a-kind (four cards with the same symbol: 7, 8, 9, 10, J, Q, K or A) by drawing 5 cards in R


I tried in this way, but it doesn't work, because I can't match the different cards in the function sum. How can I match the 4 cards?

suits <- c("Clubs", "Diamonds", "Hearts", "Spades")
cards <-c("Ace", 7:10, "Jack", "Queen", "King")

deck2 <- rep(cards, 4)

prob4cards <- function()
{
prob4cards <- sample(deck2, size= 5, replace = FALSE)
sum(prob4cards[,1] == prob4cards[,2] == prob4cards[,3]== prob4cards[,4])
}

Solution

  • The probability of 4 cards being the same out of 5 cards drawn can be found by -

    prob4cards <- function(deck) {
      prob4cards <- sample(deck, size= 5, replace = FALSE)
      any(table(prob4cards) == 4)
    }
    
    mean(replicate(10000, prob4cards(deck2)))
    

    Increase the count in replicate to get more accurate results.