Skip to content

Instantly share code, notes, and snippets.

@parrot-studio
Created July 25, 2012 01:50
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 parrot-studio/3173903 to your computer and use it in GitHub Desktop.
Save parrot-studio/3173903 to your computer and use it in GitHub Desktop.
RO・サマスペ2012の宿題シミュレーション
# 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)}"
@parrot-studio
Copy link
Author

結果:
ruby homework.rb 5 100000
pattern1 : 20.01
pattern2 : 58.63

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