Last active
May 12, 2021 23:06
-
-
Save Tempate/ddcc9db912bf2b548355edfd8cfa2255 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
def throw_die(count, sides) | |
# Throw die randomly and add them up | |
count.times.sum{ rand(1..sides) } | |
end | |
def simulate(m, n, sides) | |
k = 100000 | |
wins = k.times.count{ | |
throw_die(m, sides) > throw_die(n, sides) | |
} | |
wins.fdiv(k).round(2) | |
end | |
def calculate(m, n, sides) | |
m_probs = probabilities(m, sides) | |
n_probs = probabilities(n, sides) | |
# Calculate the probability of the sum of | |
# m-die being greater than the sum of n-die | |
m_probs.map.with_index(-1){ |prob, i| | |
prob * n_probs[..i.clamp(0..)].sum | |
}.sum.round(2) | |
end | |
def probabilities(count, sides) | |
if count == 1 | |
return [1.fdiv(sides)] * sides | |
end | |
previous_probs = probabilities(count - 1, sides) | |
# Shift the probabilities to account for the new possible results | |
shifted_probs = sides.times.map{ |number| | |
prefix = Array.new(number + 1, 0) | |
sufix = Array.new(sides - number - 1, 0) | |
prefix + previous_probs + sufix | |
} | |
# Update the probability of every result | |
shifted_probs.transpose.map{ |number_probs| number_probs.sum / sides } | |
end | |
puts simulate(4, 3, 6) | |
puts calculate(4, 3, 6) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment