Skip to content

Instantly share code, notes, and snippets.

@dzil123
Created April 13, 2020 06:50
Show Gist options
  • Save dzil123/e9aa5e5585cf0da248321be83e0290c1 to your computer and use it in GitHub Desktop.
Save dzil123/e9aa5e5585cf0da248321be83e0290c1 to your computer and use it in GitHub Desktop.
Pythagorean Theorem
use std::fmt::{self, Display};
fn main() {
let b = None;
let a = None;
let c = Some(5.0);
let ans = pyth(a, b, c).unwrap();
println!("Answer: {}", ans);
println!("{:?}", ans);
}
type FLOAT = f32; // Could be f64 for double precision
#[derive(Debug)]
enum Output {
Integer(u32),
Float(FLOAT),
}
impl Output {
fn new(val: FLOAT) -> Self {
let root = val.sqrt();
if (root.round() - root).abs() < 1e-4 {
Output::Integer(root.round() as _)
} else {
Output::Float(val)
}
}
}
impl Display for Output {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> fmt::Result {
match self {
Output::Integer(int) => write!(f, "{}", int),
Output::Float(float) => write!(f, "√{:.}", float),
}
}
}
type IN = Option<FLOAT>;
fn pyth(a: IN, b: IN, c: IN) -> Option<Output> {
let out = if c.is_none() {
a?.powi(2) + b?.powi(2)
} else {
c?.powi(2) - a.or(b)?.powi(2)
};
Some(Output::new(out))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment