
# 6張一費, 6張二費, 5張3費
cards <- c(rep(1, 6), rep(2, 6), rep(3, 5))
# 補滿30張
cards <- c(cards, rep("X", 30 - length(cards)))
# 每張取名字
names(cards) <- seq_along(cards)

# 起手一張二費與三張高費
init.cards <- cards[c(7, 18, 19, 20)]
# 牌庫剩下的牌。重洗的時候只會從這邊抽
left.cards <- cards[setdiff(names(cards), names(init.cards))]

roger <- function() {
  # 換四張牌
  init.new <- sample(left.cards, 4, FALSE)
  # 燙兩次
  tom <- sample(cards[setdiff(names(cards), names(init.new))], 2, FALSE)
  # 第一回合的牌（前五張），與第二回合抽到的牌
  c(init.new, tom)
}

shadesea <- function() {
  # 換三張牌保留二費
  init.new <- c(init.cards[1], head(sample(left.cards, 3, FALSE)))
  # 燙兩次
  tom <- sample(cards[setdiff(names(cards), names(init.new))], 2, FALSE)
  # 第一回合的牌（前五張），與第二回合抽到的牌
  c(init.new, tom)
}
checker <- list(
  has.1 = function(x) {
    "1" %in% head(x, 5)
  },
  has.2 = function(x) {
    "2" %in% head(x, 5)
  },
  has.12 = function(x) {
    ("1" %in% head(x, 5)) | ("2" %in% head(x, 5))
  },
  # 2+2
  has.2.2 = function(x) {
    sum(x == "2") >= 2
  },
  # 1+2
  has.1.2 = function(x) {
    ("1" %in% head(x, 5)) & ("2" %in% x)
  },
  has.2.1 = function(x) {
    ("2" %in% head(x, 5)) & ("1" %in% x)
  },
  has.2.11 = function(x) {
    ("2" %in% head(x, 5)) & (sum("1" == x) >= 2)
  },
  has.1.1 = function(x) {
    sum(x == "1") >= 2
  },
  has.1.11 = function(x) {
    sum(x == "1") >= 3
  },
  has.11.11 = function(x) {
    sum(x == "1") >= 4
  },
  has.1.3 = function(x) {
    ("1" %in% head(x, 5)) & ("3" %in% x)
  },
  has.1.12 = function(x) {
    ("1" %in% head(x, 5)) & (sum(x =="1") >= 2) & ("2" %in% x)
  },
  # 滿水晶
  crystal.full = function(x) {
    checker$has.1.2(x) | checker$has.2.2(x) | checker$has.1.11(x) | checker$has.11.11(x) | checker$has.1.3(x) | checker$has.1.12(x)
  },
  # 有做事
  no.idle = function(x) {
    checker$crystal.full(x) | checker$has.2.1(x) | checker$has.1.1(x)
  }
)
tasks <- expand.grid(sample = c("roger", "shadesea"), fname = names(checker))
task.name <- apply(tasks, 1, paste, collapse = "-")
result <- sapply(1:20, function(i, n) {
  sample <- list(
    roger = lapply(seq_len(n), function(i) roger()),
    shadesea = lapply(seq_len(n), function(i) shadesea())
  )
  result <- apply(tasks, 1, function(x) {
    mean(sapply(sample[[x[1]]], checker[[x[2]]]))
  })
  names(result) <- task.name
  result
}, n = 100) # 免費的計算資源有限，所以調降樣本數
# result
result2 <- apply(result, 1, function(x) {
  c(mean(x) - 2 * sd(x), mean(x), mean(x) + 2 * sd(x))
})
rownames(result2) <- c("95% Confidence Interval(lower)", "Estimated Probability", "95% Confidence Interval(upper)")
result2



