Riddler Classic
Here are four questions of increasing difficulty about finding sticks in the woods, breaking them and making shapes:
Problem 1
If you break a stick in two places at random, forming three pieces, what is the probability of being able to form a triangle with the pieces?
Solution
from random import random
runs, s = 1000000, 0
for _ in range(runs):
r1,r2 = random(), random()
if r2 > r1:
x1, x2, x3 = r1, r2 - r1, 1 - r2
else:
x1, x2, x3 = r2, r1 - r2, 1 - r1
if (x1 + x2 > x3) and (x2 + x3 > x1) and (x1 + x3 > x2): s += 1
print(s/runs)
The probability is .
Problem 2
If you select three sticks, each of random length (between 0 and 1), what is the probability of being able to form a triangle with them?
Solution
from random import random
runs, s = 1000000, 0
for _ in range(runs):
x1,x2,x3 = random(), random(), random()
if (x1 + x2 > x3) and (x2 + x3 > x1) and (x1 + x3 > x2): s += 1
print(s/runs)
The probability is .
Problem 3
If you break a stick in two places at random, what is the probability of being able to form an acute triangle — where each angle is less than 90 degrees — with the pieces?
Solution
from random import random
runs, s = 1000000, 0
for _ in range(runs):
r1,r2 = random(), random()
if r2 > r1:
x1, x2, x3 = r1, r2 - r1, 1 - r2
else:
x1, x2, x3 = r2, r1 - r2, 1 - r1
if (x1 + x2 > x3) and (x2 + x3 > x1) and (x1 + x3 > x2):
cos_a = (x1**2 + x2**2 - x3**2)/2*x1*x2
cos_b = (x1**2 + x3**2 - x2**2)/2*x1*x3
cos_c = (x2**2 + x3**2 - x1**2)/2*x2*x3
if cos_a >= 0 and cos_b >= 0 and cos_c >=0:
s += 1
print(s/runs)
The probability is .
Problem 4
If you select three sticks, each of random length (between 0 and 1), what is the probability of being able to form an acute triangle with the sticks?
Solution
from random import random
runs, s = 1000000, 0
for _ in range(runs):
x1, x2, x3 = random(), random(), random()
if (x1 + x2 > x3) and (x2 + x3 > x1) and (x1 + x3 > x2):
cos_a = (x1**2 + x2**2 - x3**2)/2*x1*x2
cos_b = (x1**2 + x3**2 - x2**2)/2*x1*x3
cos_c = (x2**2 + x3**2 - x1**2)/2*x2*x3
if cos_a >= 0 and cos_b >= 0 and cos_c >=0:
s += 1
print(s/runs)
The probability is .