Created
June 21, 2021 02:30
-
-
Save suchowan/89510810edffe6f43a5d4d8494a51e82 to your computer and use it in GitHub Desktop.
勝敗経緯パターンの試行
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
module Static | |
refine Array do | |
# 平均 | |
def mean | |
self.inject(&:+) / self.length | |
end | |
# 標準偏差 | |
def sdev | |
m = self.mean | |
Math.sqrt(self.inject(0.0) {|s,e| s += (e-m)**2} / (self.length-1)) | |
end | |
alias :_permutation :permutation | |
# 順列生成 | |
# count なし: すべての場合, あり: 乱数で count 回生成 | |
def permutation(count=nil, &block) | |
if count && count > self.length | |
count.times do | |
random = self.dup | |
perm = [] | |
until random.empty? | |
perm << random.delete_at(rand(0...random.length)) | |
end | |
block.call(perm) | |
end | |
else | |
self._permutation(count, &block) | |
end | |
end | |
end | |
end | |
using Static | |
# 勝敗経緯パターンに対応する順位の配列 | |
def order(perm) | |
cases = Hash.new {|h,k| h[k]=[]} | |
cases[''] = perm.dup | |
rest = perm.length | |
while rest > 1 do | |
cases.keys.each do |k| | |
v = cases.delete(k) | |
until v.empty? do | |
a, b, *v = v | |
cases[k + '○'] << [a,b].min | |
cases[k + '×'] << [a,b].max | |
end | |
end | |
rest /= 2 | |
end | |
cases | |
end | |
# 勝敗経緯パターンの試行 | |
def trial(n, count=nil) | |
trials = Hash.new {|h,k| h[k] = []} | |
(2..2**n).to_a.map(&:to_f).permutation(count) do |perm| | |
order([1.0]+perm).each_pair do |k, v| | |
trials[k] << v.first | |
end | |
end | |
trials | |
end | |
# 8人櫓 (全順列網羅) | |
trials = trial(3) | |
trials.length.times do |i| | |
puts ' %2d %s %7.4f %7.4f' % [i+1, trials.keys[i], | |
trials.values[i].mean, trials.values[i].sdev] # => | |
# 1 ○○○ 1.0000 0.0000 | |
# 2 ○○× 2.6000 0.8001 | |
# 3 ○×○ 3.0571 0.8601 | |
# 4 ○×× 5.3429 0.9841 | |
# 5 ×○○ 3.6571 0.9841 | |
# 6 ×○× 5.9429 0.8601 | |
# 7 ××○ 6.4000 0.8001 | |
# 8 ××× 8.0000 0.0000 | |
end | |
# 16人櫓 (10万回試行) | |
trials = trial(4,100000) | |
trials.length.times do |i| | |
puts ' %2d %s %7.4f %7.4f' % [i+1, trials.keys[i], | |
trials.values[i].mean, trials.values[i].sdev] # => | |
# 1 ○○○○ 1.0000 0.0000 | |
# 2 ○○○× 2.7772 1.0512 | |
# 3 ○○×○ 3.3264 1.1702 | |
# 4 ○○×× 6.4880 1.8770 | |
# 5 ○×○○ 4.0833 1.4004 | |
# 6 ○×○× 7.4572 1.8547 | |
# 7 ○××○ 8.2784 1.8964 | |
# 8 ○××× 11.9042 1.7225 | |
# 9 ×○○○ 5.0948 1.7260 | |
# 10 ×○○× 8.7218 1.8861 | |
# 11 ×○×○ 9.5457 1.8576 | |
# 12 ×○×× 12.9170 1.4003 | |
# 13 ××○○ 10.5087 1.8749 | |
# 14 ××○× 13.6717 1.1694 | |
# 15 ×××○ 14.2254 1.0497 | |
# 16 ×××× 16.0000 0.0000 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment