Created
July 25, 2012 01:50
-
-
Save parrot-studio/3173903 to your computer and use it in GitHub Desktop.
RO・サマスペ2012の宿題シミュレーション
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
# n=5で50%のつもり | |
def hit?(n) | |
rand(10) <= (n-1) ? true : false | |
end | |
# パターン1:かぶりなし=10回成功したら終わり | |
def pattern1(r) | |
count = 0 | |
hit = 0 | |
loop do | |
break if hit >= 10 | |
count += 1 | |
next unless hit?(r) | |
hit += 1 | |
end | |
count | |
end | |
# パターン2:かぶりあり | |
def pattern2(r) | |
count = 0 | |
items = [] | |
loop do | |
break if items.size >= 10 | |
count += 1 | |
next unless hit?(r) | |
i = rand(10) # 0-9まで出る | |
items << i unless items.include?(i) | |
end | |
count | |
end | |
# main | |
hit_ratio = ARGV[0].to_i | |
exec_count = ARGV[1].to_i | |
r1 = 0 | |
r2 = 0 | |
exec_count.times do | |
r1 += pattern1(hit_ratio) | |
r2 += pattern2(hit_ratio) | |
end | |
puts "pattern1 : #{(r1.to_f/exec_count.to_f).round(2)}" | |
puts "pattern2 : #{(r2.to_f/exec_count.to_f).round(2)}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
結果:
ruby homework.rb 5 100000
pattern1 : 20.01
pattern2 : 58.63