Search code examples
rstatisticsprobability

Find four of a kind through simulation in r


  • There is something off about my function and I am not sure what it is.... any help would be greatly appreciated
#Create a deck of cards
suits <- c("Diamonds", "Clubs", "Hearts", "Spades")
numbers <- c("Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King")
deck <- expand.grid(number = numbers, Suit = suits)

#simulate four of a kind in a hand of 5 cards
sim_four <- function(deck){
    sim_four <- sample(deck, size = 5, replace = FALSE)
    any(table(sim_four) == 4)

}

mean(replicate(10000, sim_four(deck)))```

Solution

  • I would do something like that:

    sim_four <- function(deck){
      ind <- sample(1:52,size = 5,replace = F)
      sim_four <- deck[ind,]
      any(table(sim_four$number) == 4)
    }
    

    you need to sample from the number of cards and then select the card based on the indices previously sampled. When you look for 4 equal cards (in the poker sense), you need to look for the numbers and not for the suits