Skip to content

Instantly share code, notes, and snippets.

@Frago9876543210
Created November 30, 2019 18:46
Show Gist options
  • Save Frago9876543210/77161e0c8965205ee1f03d09f627d820 to your computer and use it in GitHub Desktop.
Save Frago9876543210/77161e0c8965205ee1f03d09f627d820 to your computer and use it in GitHub Desktop.
resistance-calculator in rust
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