プログラマ向けの身近な #数学の問題 です。
Twitterに自動投稿するbotを作りました。1000個の異なるテキストを用意し、1日に2回ランダムにツイートします。1ヶ月(31日)でランダムにツイートする62個のうちダブる確率(2個以上同じツイートをする確率)は約何%でしょうか。
TWEETS = 1000 | |
ratio = 1.0 | |
TWEETS.times do |count| | |
ratio *= (TWEETS.to_r - count) / TWEETS | |
printf("%d個のテキストからランダムに%d個ツイートすると約%.0fパーセントの確率でダブります。\n", TWEETS, count + 1, 100 * (1 - ratio)) | |
end |
シミュレーション
TRIALS = 100000
TWEETS = 1000
TIMES = 62
def trial
a = []
TIMES.times do |n|
r = rand(TWEETS)
if a.include?(r)
return :conflict
end
a << r
end
return :notconflict
end
conflicts = 0
TRIALS.times do
if trial == :conflict
conflicts += 1
end
end
printf("%f\n", 100 * (conflicts.to_r / TRIALS))
実行するたびに細かい値は変わるけど、85.5%くらい
# => 85.476000
# => 85.566000
# => 85.667000
# => 85.451000
# => 85.447000
TWEETS = 1000
ratio = 1.0
62.times do |count|
ratio *= (TWEETS.to_r - count) / TWEETS
puts "#{count + 1}: #{1 - ratio}"
end
#=> 62: 0.8549973594124946
ということで、62個だと、約85%