Skip to content

Instantly share code, notes, and snippets.

@doryokujin
Created May 8, 2012 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save doryokujin/2637068 to your computer and use it in GitHub Desktop.
Save doryokujin/2637068 to your computer and use it in GitHub Desktop.
coupon collector's problem
as.prob <- function(weight){
return(weight/sum(weight))
}
expt.comp <- function(input){
n <- length(input)
g <- function(i,n,input){
(-1)**(n-1-i)*1/(1-apply(combn(input,i),2,sum))
}
tmp <- sapply(seq(0,n-1),function(i){
g(i,n,input)
})
res <- sum(sapply(tmp,sum))
return(res)
}
##### 3種類 #####
# 今3種類のアイテムをコンプするのにも、等確率に出る設定よりも異なる確率を設定した方がコンプに必要な期待回数は増えていくことがわかる。
# 1.等確率 (1/3, 1/3, 1/3)
weight <- c(1,1,1)
expt.comp(as.prob(weight))
# [1] 5.5
# もちろんこの結果は2.1での計算方法 nH(n) の結果と同じ
3 * harmonic(3)
# [1] 5.5
# 2. (1/6, 1/3, 1/2)
weight <- c(1,2,3)
expt.comp(as.prob(weight))
# [1] 7.3
# 3. (1/10, 4/10, 5/10)
weight <- c(1,4,5)
expt.comp(as.prob(weight))
# [1] 10.72222
# 4. (1/10, 1/10, 4/5)
weight <- c(1,1,8)
expt.comp(as.prob(weight))
# [1] 15.02778
##### 20種類 #####
# もし1回300円で20種類のアイテムを用意したとすると、5個のレアアイテムと15個の通常アイテムという設定で、コンプまでに必要な金額を10万円とすることができる。
# 1. 等確率の場合
weight <- c(rep(1,20))
times <- expt.comp(as.prob(weight))
times
# [1] 71.95479 [回]
300*times
# [1] 21586.44 [円]
# 2. 通常より10倍出にくいレアアイテム5個と15個の通常アイテム
# (1,1,1,1,1,10,...,10)
weight <- c(rep(1,5),rep(10,15))
times <- expt.comp(as.prob(weight))
times
# [1] 353.9834
300*times
# [1] 106195
##### 10種類 #####
# 1. 等確率の場合
weight <- c(rep(1,10))
times <- expt.comp(as.prob(weight))
times
# [1] 29.28968
300*times
# [1] 8786.905
# 2. 通常より30倍出にくいレアアイテムを3個も用意すれば10種類あれば十分
# (1,1,1,30,30,...,30)
weight <- c(rep(1,3),rep(30,7))
times <- expt.comp(as.prob(weight))
times
#[1] 390.5077
300*times
# [1] 117152.3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment