匿名質問の確率の問題をRubyで解いてみた。

 匿名質問の確率の問題Rubyで解いてみました。(^_^;

●probability01.rb

# encoding: Shift_JIS
# probability01.rb
require "mathn"
total=0
c0=c1=c2=c3=0
for a in 1..3 do  # 1:A; 2:B; 3:C
  for b in 1..3 do
    for c in 1..3 do
      cnt=0
      total+=1
      cnt+=1 if a==1
      cnt+=1 if b==2
      cnt+=1 if c==3
      case cnt
      when 0 then c0+=1
      when 1 then c1+=1
      when 2 then c2+=1
      when 3 then c3+=1
      end
    end
  end
end

print "このような組の数が2組である確率は「",c2/total,"\n"
print "1組である確率は「",c1/total,"」であり、\n"
print "このような組がない確率が「",c0/total,"」である。\n"

●実行結果

このような組の数が2組である確率は「2/9」
1組である確率は「4/9」であり、
このような組がない確率が「8/27」である。

※参考URL
Rubyで値をインクリメントするのにi++は使えない? - QA@IT
http://qa.atmarkit.co.jp/q/36
●kazkaz diary - Ruby で分数計算 - Ruby で分数計算 , 第23回 Ruby ...
http://www.ync-net.co.jp/~kaz/diary/?date=20080213

たのしいRuby 第3版

たのしいRuby 第3版

Ruby逆引きハンドブック

Ruby逆引きハンドブック