Created
November 30, 2019 18:46
-
-
Save Frago9876543210/77161e0c8965205ee1f03d09f627d820 to your computer and use it in GitHub Desktop.
resistance-calculator in rust
This file contains hidden or 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 Connection::*; | |
type Resistor = f64; | |
enum Connection { | |
Wrapper(Vec<Self>), | |
Parallel(Vec<Self>), | |
Serial(Vec<Resistor>), | |
} | |
impl Connection { | |
fn equivalent_resistance(&self) -> f64 { | |
let mut eq = 0.0; | |
match self { | |
Wrapper(connections) => { | |
for connection in connections { | |
eq += connection.equivalent_resistance(); | |
} | |
} | |
Parallel(connections) => { | |
let mut temp = 0.0; | |
for connection in connections { | |
temp += 1.0 / connection.equivalent_resistance(); | |
} | |
eq += 1.0 / temp; | |
} | |
Serial(elements) => { | |
for resistance in elements { | |
eq += *resistance; | |
} | |
} | |
} | |
eq | |
} | |
} | |
fn cast(vec: Vec<i32>) -> Vec<Resistor> { | |
vec.iter().map(|&x| x as Resistor).collect() | |
} | |
macro_rules! wrapper { | |
($($x:expr),*) => ( | |
Wrapper(vec![$($x),*]); | |
); | |
} | |
macro_rules! serial { | |
($($x:expr),*) => ( | |
Serial(cast(vec![$($x),*])); | |
); | |
} | |
macro_rules! parallel { | |
($($x:expr),*) => ( | |
Parallel(vec![$($x),*]) | |
) | |
} | |
fn main() { | |
let connection = wrapper!(parallel!( | |
serial!(2, 1, 3), | |
parallel!(serial!(4), serial!(5)) | |
)); | |
println!("{:.2}", connection.equivalent_resistance()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment