solve all sides of a triangle in swift

To solve all sides of a triangle, we can use the Law of Cosines, which states that the square of a side of a triangle is equal to the sum of the squares of the other two sides, minus twice the product of those sides and the cosine of the angle between them.

To do this in Swift, we can define a function that takes in the three sides of the triangle and the angles opposite those sides as parameters, and returns the remaining sides:

main.swift
func solveTriangle(a: Double?, b: Double?, c: Double?, alpha: Double?, beta: Double?, gamma: Double?) -> (Double?, Double?, Double?) {
    var a = a, b = b, c = c, alpha = alpha, beta = beta, gamma = gamma
    
    if let alpha = alpha { // if we have alpha, we can use Law of Cosines
        if let a = a, let b = b {
            c = sqrt(a*a + b*b - 2*a*b*cos(alpha))
        } else if let a = a, let c = c {
            b = sqrt(a*a + c*c - 2*a*c*cos(alpha))
        } else if let b = b, let c = c {
            a = sqrt(b*b + c*c - 2*b*c*cos(alpha))
        }
    }

    if let beta = beta { // if we have beta, we can use Law of Cosines
        if let b = b, let c = c {
            a = sqrt(b*b + c*c - 2*b*c*cos(beta))
        } else if let a = a, let c = c {
            b = sqrt(a*a + c*c - 2*a*c*cos(beta))
        } else if let a = a, let b = b {
            c = sqrt(a*a + b*b - 2*a*b*cos(beta))
        }
    }

    if let gamma = gamma { // if we have gamma, we can use Law of Cosines
        if let a = a, let c = c {
            b = sqrt(a*a + c*c - 2*a*c*cos(gamma))
        } else if let a = a, let b = b {
            c = sqrt(a*a + b*b - 2*a*b*cos(gamma))
        } else if let b = b, let c = c {
            a = sqrt(b*b + c*c - 2*b*c*cos(gamma))
        }
    }

    return (a, b, c)
}
1308 chars
36 lines

Here is an example of how to use this function:

main.swift
let sides = solveTriangle(a: 3.0, b: nil, c: 4.0, alpha: nil, beta: 90.0 * Double.pi/180.0, gamma: nil)
print(sides) // (3.0, 5.0, 4.0)
136 chars
3 lines

In this example, we are solving for the missing side b of a right triangle with sides a and c of length 3 and 4, respectively. We pass in nil for the sides we want to solve for, and the angle beta, which is opposite to the missing side, with a value of 90 degrees (converted to radians). The function returns a tuple with the three sides of the triangle, and we print it to the console. The output should be (3.0, 5.0, 4.0), which confirms that the missing side b is indeed 5 (as expected for a right triangle).

gistlibby LogSnag