Heron + Law of Cosines solution in Clear category for Strawberry Fields by jtokaz
# Heron's formula gives the area of a triangle from the lengths
# of its three sides a, b, and c.
# Area = sqrt(s*(s-a)*(s-b)*(s-c)) where s = (a+b+c)/2
s = 0.5*(a+b+c) # s is the semi-perimeter (half perimeter)
# take max with 0 before sqrt, so that small negative values (due to
# precision, step size) given 0 instead of error
# e.g. sqrt(-1e-6) = 0
# Law of cosines relates the lengths of sides of a triangle to
# an included angle.
# sides : a,b,c
# opposite angles in radiands : A, B, C
# angle A is opposite to side a; B to b; C to c
C = math.acos((a*a+b*b-c*c)/(2*a*b))
def strawberryfield(a, b, c, d):
# build a list of possible values for p, where p is the length
# of the diagonal so that d,a,p and b,c,p are two triangles
# for any x>0,y>0,z>0 such that abs(x-y) < z < x+y there exists
# a triangle with sides x,y,z
# this becomes
# abs(a-d) < p < a+d AND abs(b-c) < p < b+c
# or, alternatively max(abs(a-d),abs(b-c)) < p < min(a+d,b+c)
start, stop, step = max(abs(a-d),abs(b-c)), min(a+d,b+c), 1e-2
ps = [step*x for x in range(int(start/step),int(stop/step)+1)]
# find the value of p that maximizes the sum of the areas of the
# two triangles
p = max(ps,key=lambda p:heron_area(a,d,p) + heron_area(b,c,p))
# find the angle oppostive p in the a,d,p triangle
# convert to degrees
# and round to the tenths place
# These "asserts" are used for self-checking only and not for an auto-testing
if __name__ == '__main__':
assert(strawberryfield(100, 100, 100, 100) == 90) , "square"
assert(strawberryfield(150, 100, 150, 100) == 90) , "rectangle"
assert(strawberryfield(150, 100, 50, 100) == 60) , "trapezium"
assert(strawberryfield(203, 123, 82, 117) == 60.8) , "quadrilateral"
print("Looks good so far! . . . How does 'Check' ?")
April 20, 2018