Created
April 13, 2020 06:50
-
-
Save dzil123/e9aa5e5585cf0da248321be83e0290c1 to your computer and use it in GitHub Desktop.
Pythagorean Theorem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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