如何解决二十一点使用 R中自然 21 点的概率是丢弃“10 个钻石”、“10 个红心”、“10 个黑桃”等的所有组合为什么?
我正在尝试使用 R 来计算我在二十一点中获得自然 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","10")
facecard <- expand.grid(num = facecard,suit = suit)
facecard <- paste(facecard$num,facecard$suit)
以下是 ace 和 facecard 的样子:
## 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[,2] %in% facecard)
您会看到 "ggg" 有 48 个观察值,而它应该有 64 个。有些东西省略了所有具有 “10 颗钻石”、“10 颗心”的 16 行或组合 等
如果我将 number 向量中的“10”和 facecard 替换为 “十” 那么它就可以正常工作并给我正确的概率和数据框(64 obs)。
但我不明白为什么字符“10”不被接受,以及它在代码中的什么地方不被接受? “10”和“十”是完全一样的东西:字符。那么这里的问题是什么?
解决方法
弗利克先生是对的。您假设组合将按特定顺序排列,但可能不是。 cominations
的输出确实已经排序了,但是 facecard 字符值可以在字典上大于或小于 ace 卡,因此有些对会先有 ace,有些会先有 facecard。您仍然需要检查两者(或与一组预先订购的对进行比较)
'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(),'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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。