Skip to content

Instantly share code, notes, and snippets.

@tessro
Created August 20, 2009 16:56
Show Gist options
  • Save tessro/171195 to your computer and use it in GitHub Desktop.
Save tessro/171195 to your computer and use it in GitHub Desktop.
Triangle Problem
#!/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