Home > Software engineering >  How to draw five cards from a deck of cards and count each time we get four of a kind?
How to draw five cards from a deck of cards and count each time we get four of a kind?

Time:09-20

I'm trying to count the number of times I get four of a kind when drawing 5 cards from a deck. My code so far looks like this:

numbers2 <- c("Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King")

output <- matrix(ncol=5, nrow=10000)
for(i in 1:10000){
  output[i,] <- sample(numbers2, 5, replace = FALSE)
}
df <- data.frame(output)

df <- data_frame(output)

At this point, I'm stuck, as I don't know how to count the rows in which 4 values are repeated. I didn't create an actual deck with suits because that way I don't have to deal with drawing a fifth same card if I do it with replacement.

CodePudding user response:

set.seed(123)
output <- replicate(1e5, sample(numbers2, 5, replace = FALSE))
output[, 1:10]
#      [,1]    [,2]    [,3]    [,4]    [,5]    [,6]   [,7]    [,8]   [,9]    [,10]
# [1,] "Five"  "Three" "Ace"   "Five"  "King"  "Ten"  "Two"   "Nine" "Eight" "Queen"
# [2,] "Two"   "Jack"  "Two"   "Two"   "Seven" "Ace"  "Six"   "Two"  "Ace"   "Queen"
# [3,] "Queen" "Two"   "Queen" "King"  "Three" "Four" "Three" "Ten"  "Seven" "Eight"
# [4,] "Ace"   "Four"  "King"  "Nine"  "Nine"  "Four" "Six"   "Ten"  "Queen" "Three"
# [5,] "Three" "Jack"  "Ace"   "Three" "Six"   "King" "Seven" "Ace"  "Ace"   "Five"

df <- as.data.frame(output)

You could stack each sample of cards together as a 2-column dataframe and pass it into table. It will build a contingency table of the counts of 13 numbers in each sample. Then table(...) == 4 finds where a four of a kind appears.

sum(table(stack(df)) == 4)
# [1] 51
  • Related