Skip to content

Instantly share code, notes, and snippets.

@ValentinWalter
Last active November 29, 2020 20:22
Show Gist options
  • Save ValentinWalter/a91d53020bb74ec61baf6c09845ba415 to your computer and use it in GitHub Desktop.
Save ValentinWalter/a91d53020bb74ec61baf6c09845ba415 to your computer and use it in GitHub Desktop.
QuadraticFormula implemented in Swift
//
// QuadraticFormula.swift
// Convenience around the QuadraticFormula
//
// Created by Valentin Walter on 11/12/20.
//
import Foundation
/// Provides convenience around the [Quadratic Formula](https://en.wikipedia.org/wiki/Quadratic_formula).
///
/// Given a general quadratic equation of the form
///
/// ax² + bx + c = 0
///
/// with x representing an unknown, a, b and c representing
/// constants with a ≠ 0, the quadratic formula is:
///
/// x = (-b ± √(b² - 4ac)) / 2a
///
struct QuadraticFormula: CustomStringConvertible {
/// The `a` in `ax² + bx + c = 0`. Default is 1.
var a: Double = 1
/// The `b` in `ax² + bx + c = 0`. Default is 0.
var b: Double = 0
/// The `c` in `ax² + bx + c = 0`. Default is 0.
var c: Double = 0
/// The first solution to the formula, if any.
var x1: Double? { roots.x1 }
/// The second solution to the formula, if any.
var x2: Double? { roots.x2 }
/// A tuple containing the two solutions `x1` and `x2`.
/// If there's only one solution, `x2` is `nil`.
/// If there's no solution both values are `nil`.
var roots: (x1: Double?, x2: Double?) {
let discriminant = ((b * b) - (4 * a * c)).squareRoot()
if discriminant > 0 {
let x1 = (-b + discriminant) / (2 * a)
let x2 = (-b - discriminant) / (2 * a)
return (x1, x2)
} else if discriminant == 0 {
return (0, nil)
} else {
return (nil, nil)
}
}
// CustomStringConvertible implementation
// Inherits documentation
var description: String {
switch calculate() {
case let (.some(x1), .some(x2)):
return "x1 is \(x1), x2 is \(x2)"
case let (.some(x), nil):
return "x is \(x)"
default:
return "No solution."
}
}
}
// --------- Terminal application loop ---------
func main() {
var formula = QuadraticFormula()
print("a:")
formula.a = Double(readLine()!) ?? 0
print("b:")
formula.b = Double(readLine()!) ?? 0
print("c:")
formula.c = Double(readLine()!) ?? 0
print(formula)
print("Repeat? (y/n)")
if readLine() == "y" {
main()
} else {
exit(0)
}
}
main()
// --------- Terminal application loop ---------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment