I want to know how can a solve an equation like 'x + 5 = 11' in swift. To give 'x = 6'. Can anyone help me out. Is is possible using NSExpression? Or should I use something else?
Thanks!
Thanks!
Here is some complete code:
gives
x + 5 = 11
x = 6.0
or
-x + 5 = 3
x = 2.0
Code Block func solve(_ a: Double, _ b: Double, _ c: Double) -> Double { // solve ax + b = c if a == 0 { if b == c { print("Any x is a solution") } else { print("no solution") } return 0.0 } else { return (Double(c - b)) / Double(a) } } func resolve(equation : String) -> Double { var equation = equation var aCoeff = 1.0 var bCoeff = 0.0 var cCoeff = 0.0 if let xRange = equation.range(of: "x") { var aStr = equation aStr.removeSubrange(xRange.lowerBound..<equation.endIndex) // remove everything after x aStr = aStr.replacingOccurrences(of: " ", with: "") if let a = Double(aStr) { aCoeff = a } else { // No number just x or -x if equation.first == "-" { aCoeff = -1.0 } else { aCoeff = 1.0 // Missing coeff, means 1 or -1 } } equation.removeSubrange(equation.startIndex...xRange.lowerBound) // keeps only after x (+ b = c) } else { // if x missing, not an equation aCoeff = 0.0 } if let equalRange = equation.range(of: "=") { var cStr = equation // The shorter, without x cStr.removeSubrange(equation.startIndex...equalRange.lowerBound) // remove everything upto =, to keep only c cStr = cStr.replacingOccurrences(of: " ", with: "") if let c = Double(cStr) { cCoeff = c } // Remove after = and keep only "+ b" var bStr = equation bStr.removeSubrange(equalRange.lowerBound..<equation.endIndex) // remove everything after = bStr = bStr.replacingOccurrences(of: " ", with: "") if let b = Double(bStr) { bCoeff = b } } return solve(aCoeff, bCoeff, cCoeff) } let equation = "- x + 5 = 3" print("Resolve", equation) let x = resolve(equation: equation) print("x =", x)
gives
x + 5 = 11
x = 6.0
or
-x + 5 = 3
x = 2.0