Skip to content

Instantly share code, notes, and snippets.

@hyuki

hyuki/README.md Secret

Last active August 14, 2021 03:37
Show Gist options
  • Save hyuki/7a85f52ecc1935e4a0b9f1b84f8174da to your computer and use it in GitHub Desktop.
Save hyuki/7a85f52ecc1935e4a0b9f1b84f8174da to your computer and use it in GitHub Desktop.
自動投稿botのツイートがダブる確率を計算するRubyスクリプト

プログラマ向けの身近な #数学の問題 です。

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
@hyuki
Copy link
Author

hyuki commented Aug 14, 2021

@hyuki
Copy link
Author

hyuki commented Aug 14, 2021

シミュレーション

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

@hyuki
Copy link
Author

hyuki commented Aug 14, 2021

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%

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment