Skip to content

Instantly share code, notes, and snippets.

@Tempate
Last active May 12, 2021 23:06
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 Tempate/ddcc9db912bf2b548355edfd8cfa2255 to your computer and use it in GitHub Desktop.
Save Tempate/ddcc9db912bf2b548355edfd8cfa2255 to your computer and use it in GitHub Desktop.
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