rbind / njtierney.com

Nick Tierney's website
http://www.njtierney.com/
8 stars 4 forks source link

revisit Monte Carlo Approximation #48

Open njtierney opened 3 years ago

njtierney commented 3 years ago

https://www.njtierney.com/post/2013/06/26/monte-carlo-approx/

And use R to simulate the probability of hands.

njtierney commented 3 years ago

Maybe something like this to start:

library(tidyverse)

deck <- crossing(
  number = c(2:10, "Jack", "Queen", "King", "Ace"),
  suit = c("Hearts", "Diamonds", "Clubs", "Spades")
) %>% 
  mutate(card = paste(number, "of", suit),
         number = factor(number, 
                         levels = c(2:10, "Jack", "Queen", "King", "Ace")),
         number_order = as.numeric(number)) %>% 
  arrange(number, suit) %>% 
  tibble::rowid_to_column("id")

deal <- function(x) x %>% slice_sample(n = 5)
deck %>% deal()
#> # A tibble: 5 x 5
#>      id number suit     card             number_order
#>   <int> <fct>  <chr>    <chr>                   <dbl>
#> 1    46 King   Diamonds King of Diamonds           12
#> 2     8 3      Spades   3 of Spades                 2
#> 3    26 8      Diamonds 8 of Diamonds               7
#> 4    35 10     Hearts   10 of Hearts                9
#> 5    47 King   Hearts   King of Hearts             12

# And now I've got to build a "hand classifier"

is_identical <- function(x) reduce(x, .f = identical)

hand <- deal(deck)

is_flush <- function(data){
  data %>% 
    pull(suit) %>% 
    is_identical()
}

hand %>% is_flush()
#> [1] FALSE

n_kind <- function(data, n_kind){
  data %>% 
  count(number) %>% 
  pull(n) %>% 
  magrittr::equals(n_kind)
}

n_pair <- function(x) sum(n_kind(x, 2))
is_pair <- function(x) n_pair(x) == 1
is_two_pair <- function(x) n_pair(x) == 2
is_three_of_a_kind <- function(x) any(n_kind(x, 3))
is_four_of_a_kind <- function(x) any(n_kind(x, 4))
is_full_house <- function(x) is_pair(x) && is_three_of_a_kind(x)

# straight
# straight flush
# royal flush (rankings of flush? 10 - Ace?)
# high card?

is_pair(hand)
#> [1] TRUE

(hand <- deal(deck))
#> # A tibble: 5 x 5
#>      id number suit     card           number_order
#>   <int> <fct>  <chr>    <chr>                 <dbl>
#> 1    14 5      Diamonds 5 of Diamonds             4
#> 2    27 8      Hearts   8 of Hearts               7
#> 3    30 9      Diamonds 9 of Diamonds             8
#> 4    47 King   Hearts   King of Hearts           12
#> 5     4 2      Spades   2 of Spades               1

is_three_of_a_kind(hand)
#> [1] FALSE
is_four_of_a_kind(hand)
#> [1] FALSE

Created on 2020-09-15 by the reprex package (v0.3.0)