Skip to content

Instantly share code, notes, and snippets.

@takehiko
Created May 19, 2015 12:00
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 takehiko/72c520e1f4d5c15a16c7 to your computer and use it in GitHub Desktop.
Save takehiko/72c520e1f4d5c15a16c7 to your computer and use it in GitHub Desktop.
Winning ratios
#!/usr/bin/env ruby
# n-win-m-match.rb : じゃんけんをm回やって,そのうちn回以上勝つ確率
# by takehikom
require "rational"
class NWinMMatch
def initialize(opt = {})
@choose = {} # 2項係数
@rate_eq = {} # match試合でちょうどwin勝する確率
@rate_ge = {} # match試合でwin勝以上する確率
@rate_one = opt[:p] || Rational(1, 2) # 1回の勝率
@match_max = opt[:match] || 5 # matchの最大値
@flag_noprint = opt[:noprint] # 各値を出力しないなら真
end
attr_reader :choose, :rate_eq, :rate_ge
attr_reader :rate_one, :match_max, :flag_noprint
def start
p = @rate_one; q = 1 - p
puts "p=#{p}=#{p.to_f}"
1.upto(@match_max) do |match|
rate2 = Rational(1)
0.upto(match) do |win|
if win == 0 || win == match
@choose[s(match, win)] = 1
else
@choose[s(match, win)] =
@choose[s(match - 1, win - 1)] +
@choose[s(match - 1, win)]
end
rate1 = p ** win * q ** (match - win) * @choose[s(match, win)]
@rate_eq[s(match, win)] = rate1
@rate_ge[s(match, win)] = rate2
rate2 -= rate1
puts "win=#{win}, match=#{match} : choose(#{match},#{win})=#{@choose[s(match, win)]} : rate1=#{@rate_eq[s(match, win)]} : rate2=#{@rate_ge[s(match, win)]}=#{@rate_ge[s(match, win)].to_f}" unless @flag_noprint
end
end
self
end
def s(a, b)
[a, b].join(":")
end
end
if __FILE__ == $0
NWinMMatch.new.start
=begin
n = NWinMMatch.new(:p => Rational(1, 3), :match => 100, :noprint => false).start
h = n.rate_ge
nearhalf_key = h.keys.sort_by {|item| (0.5 - h[item].to_f).abs}.first
nearhalf = h[nearhalf_key]
puts "#{nearhalf_key} : #{nearhalf.to_f}"
=end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment