二十一点(使用 R)中自然 21 的概率是掉落“10 个方块”、“10 个红心”、“10 个黑桃”等的所有组合。为什么?

Probability of a natural 21 in blackjack (using R) is dropping all combinations of "10 diamonds", "10 hearts", "10 spades", etc. WHY?

我正在尝试使用 R 找出我在 Blackjack 中获得自然 21 的概率(即,一张 A 牌和一张花牌)。

这是我的代码:

library(tidyverse)
library(gtools)

## step 1: build a deck of cards

suit<-c("diamonds","clubs","hearts","spades")

number<-c("ace","2", "3", "4", "5", "6", "7", "8", "9", "10", "jack", "queen", "king")

expand<-expand.grid(number=number, suit=suit)

deckofcards<-paste(expand$number,expand$suit)

## step 2: build a vector to be compared against

aces <- paste("ace", suit)
facecard <- c("king", "queen", "jack", "10")
facecard <- expand.grid(num = facecard, suit = suit)
facecard <- paste(facecard$num, facecard$suit)

这是 acesfacecard 的样子:

## find probability of one aces and one facecard

hands <- combinations(52, 2, v=deckofcards) # all possible hands

mean(hands[,1] %in% aces & hands[,2] %in% facecard) # this is the probability

我的代码产生的概率是 0.0361991,但它应该是 0.04826546。我发现最后一行有一个问题,无法读取 "10 方块"、"10 心"、"10 黑桃"、"10 梅花"。你可以在这里看到它:

## find the problem: there should be 64 obs

hands_df<-as.data.frame(hands)
ggg<- hands_df %>% filter(hands[,1] %in% aces & hands[,2] %in% facecard)

您会看到 "ggg" 有 48 个观察值,而它应该有 64 个。有些东西忽略了所有 16 行或具有 "10 的组合钻石”、“10 颗心”、等等

如果我将 number 向量中的“10”和 facecard 替换为 “ten” 然后它工作正常并给了我正确的概率和数据帧 (64 obs)。

但是我不明白为什么字符“10”不被接受,代码中哪里不被接受? “10”和“十”都是完全一样的东西:字符。那么这里有什么问题呢?

Mr​​Flick 是正确的。您假设组合将按特定顺序排列,但事实可能并非如此。确实 cominations 的输出已经排序,但是面牌字符值在词法上可以大于或小于 ace 牌,因此一些对将首先获得 ace,而一些将首先获得面牌。您仍然需要检查两者(或与一组预先订购的对进行比较)

'10 diamonds' > 'ace diamonds'
# [1] FALSE
'king diamonds' > 'ace diamonds'
# [1] TRUE

在这里你可以看到 'ace diamonds' 可以在两列中的任何一列,'10 diamonds' 的一侧和 'king diamonds' 的另一侧,正如你根据上面的比较所期望的那样.

hands %>% 
  as.data.frame %>% 
  filter(if_any(everything(), str_detect, 'ace'),
         if_all(everything(), str_detect, 'diamonds'))

#              V1             V2
# 1   10 diamonds   ace diamonds
# 2    2 diamonds   ace diamonds
# 3    3 diamonds   ace diamonds
# 4    4 diamonds   ace diamonds
# 5    5 diamonds   ace diamonds
# 6    6 diamonds   ace diamonds
# 7    7 diamonds   ace diamonds
# 8    8 diamonds   ace diamonds
# 9    9 diamonds   ace diamonds
# 10 ace diamonds  jack diamonds
# 11 ace diamonds  king diamonds
# 12 ace diamonds queen diamonds

更改代码以检查两者给出预期结果

mean((hands[,1] %in% aces & hands[,2] %in% facecard) |
       (hands[,2] %in% aces & hands[,1] %in% facecard)) # this is the probability
# [1] 0.04826546

如果您熟悉多元超几何分布,您也可以使用具有该功能的包跳过大量编码

library(extraDistr)

dmvhyper(c(1, 1, 0), (52/13)*c(1, 4, 8), 2)
# [1] 0.04826546