Skip to content

Instantly share code, notes, and snippets.

@bdkosher
Created April 10, 2021 01:53
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 bdkosher/ed5614b2450e20dcad803489957eeef6 to your computer and use it in GitHub Desktop.
Save bdkosher/ed5614b2450e20dcad803489957eeef6 to your computer and use it in GitHub Desktop.
If it rains 2 out of 9 days, what is the probability the two days are consecutive.
// these 9 characters represent our days: 2 days of rain ('R') and 7 days of dryness ('D')
def days = 'RRDDDDDDD' as List
// number of trials to run; the bigger the number, the more accurate the probability
int trials = 10000
// counter for the number of consecutive rainy days we see
int consecutiveRainyDays = 0
// run the trials
(1..trials).each {
// randomize the ordering of rainy and dry days
days.shuffle()
// if the ordering contains two Rs in a row, increment count of consecutive rainy days
if (days.join('').contains('RR')) ++consecutiveRainyDays
}
// calculate and display the probability
def probability = consecutiveRainyDays / trials
println "Probability that 2 rainy days out of 9 are consecutive: $probability"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment