Two Kings in a Deck – The Simulation

Let’s build an R simulation to verify the results obtained in the previous post.

Step 1: Create a deck of cards

suits <- c("Diamonds", "Spades", "Hearts", "Clubs")
numbers <- c("Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King")
deck <- expand.grid(Number = numbers, Suit = suits)
deck <- paste(deck$Number, deck$Suit)
"Ace Diamonds"   "Deuce Diamonds" "Three Diamonds" "Four Diamonds"  "Five Diamonds"  "Six Diamonds"   "Seven Diamonds" "Eight Diamonds" "Nine Diamonds"  "Ten Diamonds"   "Jack Diamonds"  "Queen Diamonds" "King Diamonds"  "Ace Spades"     "Deuce Spades"   "Three Spades"  "Four Spades"    "Five Spades"    "Six Spades"     "Seven Spades"   "Eight Spades"   "Nine Spades"    "Ten Spades"     "Jack Spades"   
"Queen Spades"   "King Spades"    "Ace Hearts"     "Deuce Hearts"   "Three Hearts"   "Four Hearts"    "Five Hearts"    "Six Hearts"    "Seven Hearts"   "Eight Hearts"   "Nine Hearts"    "Ten Hearts"     "Jack Hearts"    "Queen Hearts"   "King Hearts"    "Ace Clubs"     
"Deuce Clubs"    "Three Clubs"    "Four Clubs"     "Five Clubs"     "Six Clubs"      "Seven Clubs"    "Eight Clubs"    "Nine Clubs"    "Ten Clubs"      "Jack Clubs"     "Queen Clubs"    "King Clubs" 

Step 2: Identify the positions containing the ‘string’. Here is an example.

green <- c("Green Wood", "Green paper", "Red Wood", "Green chilly", "Light green")
grep("Green", green, ignore.case = TRUE)
1 2 4 5

The vector ‘green’ carries the string ‘green’ in its 1, 2, 4 and 5 columns. 

Step 3: Find the difference between the identified column numbers and check if 1 appears anywhere (suggesting they belong consecutively). 

any(diff(grep("Green", green, ignore.case = TRUE)) ==1)
TRUE

Step 4: Apply the scheme to the deck of cards, run it a million times, and find the average number of times the ‘any’ command gave ‘TRUE’.

itr <- 1000000

card_match <- replicate(itr, {
  shuffle <- sample(deck, 52, replace = FALSE)
  mat <- grep("King", shuffle, ignore.case = TRUE)
  consec <- diff(mat)
  
  if(any(consec == 1)) {
    counter <- 1 
  }else{
    counter <- 0
  }
})

mean(card_match)
0.216743

Not far from what we got analytically.