rdcl_aoc_helpers/math/polynomial/
impl_fmt.rs

1use std::cmp::Ordering;
2use std::fmt;
3
4use crate::math::polynomial::Polynomial;
5
6impl fmt::Display for Polynomial {
7    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8        let n = self.degree();
9        if n == 0 {
10            write!(f, "{}", self.coefficients[0])?;
11        } else {
12            write!(
13                f,
14                "{}{}",
15                fmt_lead_coefficient(self.coefficients[0]),
16                fmt_exponent(n)
17            )?;
18            for (i, &c) in self.coefficients.iter().enumerate().skip(1) {
19                if c != 0 {
20                    write!(f, "{}{}", fmt_coefficient(c), fmt_exponent(n - i))?;
21                }
22            }
23        }
24        Ok(())
25    }
26}
27
28fn fmt_lead_coefficient(c: i64) -> String {
29    match c {
30        1 => String::new(),
31        -1 => "-".to_string(),
32        _ => c.to_string(),
33    }
34}
35
36fn fmt_coefficient(c: i64) -> String {
37    match c {
38        1 => " + ".to_string(),
39        -1 => " - ".to_string(),
40        _ => match c.cmp(&0) {
41            Ordering::Less => format!(" - {}", c.abs()),
42            _ => format!(" + {}", c),
43        },
44    }
45}
46
47fn fmt_exponent(n: usize) -> String {
48    match n {
49        0 => String::new(),
50        1 => "x".to_string(),
51        _ => format!("x^{}", n),
52    }
53}