Skip to content

Instantly share code, notes, and snippets.

@harryhanYuhao
Created April 14, 2024 09:23
Show Gist options
  • Save harryhanYuhao/8b97f2827a740b299858520091dce180 to your computer and use it in GitHub Desktop.
Save harryhanYuhao/8b97f2827a740b299858520091dce180 to your computer and use it in GitHub Desktop.
use std::fmt;
/// representing each term of the polynomial
struct Nomial {
coefficient: f64,
power: f64,
}
impl Nomial {
fn new(coefficient: f64, power: f64) -> Self {
Nomial {
coefficient,
power,
}
}
}
impl fmt::Debug for Nomial {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let coef: String = if self.coefficient == 1.0 {
if self.power != 0.0 {
"".into()
} else {
"1".into()
}
} else {
self.coefficient.to_string()
};
let power: String = if self.power == 0.0 {
"".into()
} else if self.power == 1.0 {
"x".into()
} else {
format!("x^{}", self.power.to_string())
};
write!(f, "{}{}", coef, power)
}
}
type polynomial = Vec<Nomial>;
fn differentiate(pl: &polynomial) -> polynomial {
pl.iter()
.map(|x| Nomial {
coefficient: x.coefficient * x.power,
power: x.power - 1.0,
})
.collect()
}
fn main() {
let x = Nomial {
coefficient: 1.0,
power: 1.0,
};
let twox = Nomial::new(5.0, 2.0);
let poly = vec![x, twox];
let poly = differentiate(&poly);
println!("{:?}", poly);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment