Angles of a Triangle

Problem LinkSolution Link

Intuition #

We are giving 3 sides of a supposed triangle and we want to see if we can form a triangle, and return the angles in degrees if we can.

To create a triangle from these 3 sides, we want the sum of any two sides to be greater than the third side (Triangle Inequality Theorem). If this condition is not met that means we cannot create a triangle from these 3 sides.

Wikipedia article on the theorem: https://en.wikipedia.org/wiki/Triangle_inequality

For sides a, b, c to form a triangle, all three must hold:

  1. a+b>ca + b > c
  2. a+c>ba + c > b
  3. b+c>ab + c > a

We can further and only check the condition a+b>ca + b > c if we sort the sides.

Why sorting reduces it to one check?

After sorting so that abca ≤ b ≤ c (c is the largest). Can conditions 2 and 3 ever fail?

Since c is the largest a+c>ba + c > b is automatically satisfied. Same goes for b+c>ab + c > a.

To get the angles after we are sure that we can create the triangle, we can use law of cosines:

a2=b2+c22bccos(A)b2=a2+c22accos(B)c2=a2+b22abcos(C) \begin{aligned} a^{2} &= b^{2} + c^{2} - 2bc\cos(A)\\[4pt] b^{2} &= a^{2} + c^{2} - 2ac\cos(B)\\[4pt] c^{2} &= a^{2} + b^{2} - 2ab\cos(C) \end{aligned}

Gives us:

A=arccos ⁣(b2+c2a22bc)B=arccos ⁣(a2+c2b22ac)C=arccos ⁣(a2+b2c22ab) \begin{aligned} A &= \arccos\!\left(\frac{b^{2} + c^{2} - a^{2}}{2bc}\right) \\[6pt] B &= \arccos\!\left(\frac{a^{2} + c^{2} - b^{2}}{2ac}\right) \\[6pt] C &= \arccos\!\left(\frac{a^{2} + b^{2} - c^{2}}{2ab}\right) \end{aligned}

Wikipedia article on the law: https://en.wikipedia.org/wiki/Law_of_cosines

Approach #

Complexity #

Code #

 1import (
 2	"math"
 3	"slices"
 4)
 5
 6func internalAngles(sides []int) []float64 {
 7	slices.Sort(sides)
 8
 9	a, b, c := sides[0], sides[1], sides[2]
10
11	if a+b <= c {
12		return []float64{}
13	}
14
15	// We can form a triangle
16	a2, b2, c2 := float64(a*a), float64(b*b), float64(c*c)
17
18	result := []float64{
19		math.Acos((b2+c2-a2)/float64(2*b*c)) * 180 / math.Pi,
20		math.Acos((a2+c2-b2)/float64(2*a*c)) * 180 / math.Pi,
21		math.Acos((a2+b2-c2)/float64(2*a*b)) * 180 / math.Pi,
22	}
23
24	return result
25}