Skip to content

Instantly share code, notes, and snippets.

@jeffreyiacono
Last active September 30, 2015 13:07
Show Gist options
  • Save jeffreyiacono/1795507 to your computer and use it in GitHub Desktop.
Save jeffreyiacono/1795507 to your computer and use it in GitHub Desktop.
simulation of the math problem: "If you break a straight line randomly in two places, what is the probability that you can form a triangle from the resulting three pieces?"
# simulation to calculate an answer to the question:
#
# "If you break a straight line randomly in two places, what is the probability that you can
# form a triangle from the resulting three pieces?"
#
# usage: ruby ./triangles-sim.rb [trials]
# sample output:
#
# $> ruby ./triangles-sim.rb 1000000
#
# Trials: 1000000
# Valid Triangles: 250077
# Percentage: 25.0077%
#
# Ran in 2.775591s
started = Time.new
trials = ARGV.length > 0 ? ARGV[0].to_i : 1000
triangleCount = 0
# let's assume the starting length is 1 so we can use rand
trials.times do
breaks = [rand, rand].sort
# calc the lengths
lengths = [breaks[0], breaks[1] - breaks[0], 1 - breaks[1]].sort
# add 1 if we have a valid triangle (sum of two smaller lengths must be less
# than largest length)
triangleCount += 1 if lengths[2] < lengths[0] + lengths[1]
end
pct = triangleCount.to_f / trials * 100
runtime = Time.new - started
puts
puts "Trials: #{trials}"
puts "Valid Triangles: #{triangleCount}"
puts "Percentage: #{pct}%"
puts
puts "Ran in #{runtime}s"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment