Angles of a Triangle
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:
We can further and only check the condition if we sort the sides.
Why sorting reduces it to one check?
After sorting so that (
cis the largest). Can conditions 2 and 3 ever fail?Since
cis the largest is automatically satisfied. Same goes for .
To get the angles after we are sure that we can create the triangle, we can use law of cosines:
Gives us:
Wikipedia article on the law: https://en.wikipedia.org/wiki/Law_of_cosines
Approach #
- Sort
sides. - If
a+b <= c.- Return
[].
- Return
- Return the angles using the law of cosines.
Complexity #
Time complexity: .
Space 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}