Created
August 20, 2009 16:56
-
-
Save tessro/171195 to your computer and use it in GitHub Desktop.
Triangle Problem
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
#!/usr/bin/ruby | |
numOfTrials = 10000 | |
numTriangles = 0 | |
numOfTrials.times do | |
# generate two random breaks, in order | |
breaks = [ rand, rand ].sort | |
# load the length calculations via the breaks into an "lengths" array | |
# order the lengths | |
lengths = [ | |
breaks[0], | |
breaks[1] - breaks[0], | |
1 - breaks[1] | |
].sort | |
# add 1 to triangle var if we have a triangle | |
numTriangles += 1 if lengths[2] < lengths[0] + lengths[1] | |
end | |
pct = numTriangles.to_f / numOfTrials * 100 | |
puts "Number of Trials: #{numOfTrials}" | |
puts "Number of Triangles: #{numTriangles}" | |
puts "Percentage: #{pct}%" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment