From 6262cd9aab04bce1c98fd5f6ab19cd5da814dfc7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Manuel=20Tom=C3=A1s?= Date: Mon, 11 Jan 2021 08:42:04 -0300 Subject: Implement add and sub for P --- src/poly.rs | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 62 insertions(+), 1 deletion(-) (limited to 'src/poly.rs') diff --git a/src/poly.rs b/src/poly.rs index 2128d38..34444b3 100644 --- a/src/poly.rs +++ b/src/poly.rs @@ -1,6 +1,53 @@ +mod iter; + +use crate::number::Number; +use iter::Iter; +use std::cmp; use std::cmp::Ordering; +use std::ops::{Add, Sub}; +use std::iter::{Zip, Take}; + +#[derive(PartialEq, Debug)] +pub struct P(Vec); + +impl P { + fn degree(&self) -> usize { + let mut i = self.0.len() - 1; + while self.0[i] == 0.0 && i > 0 { + i -= 1; + } + i + } + + fn iter(&self) -> Iter { + Iter::new(self.0.clone()) + } + + fn zip(&self, other: &Self) -> Zip, Take> { + let deg = cmp::max(self.degree(), other.degree()) + 1; + let a = self.iter().take(deg); + let b = other.iter().take(deg); + a.zip(b) + } +} + +impl Add for &P { + type Output = P; + + fn add(self, other: Self) -> P { + P(self.zip(other).map(|(x, y)| {x + y}).collect()) + } +} + +impl Sub for &P { + type Output = P; + + fn sub(self, other: Self) -> P { + P(self.zip(other).map(|(x, y)| {x - y}).collect()) + } +} -pub type Number = f32; +//****************************REFACTORING************************************ pub type Poly = Vec; @@ -87,6 +134,20 @@ pub fn gcd(a: &Poly, b: &Poly) -> Poly { mod tests { use super::*; + #[test] + fn add_test() { + let a = P(vec![1.0]); + let b = P(vec![0.0, 0.0, 0.0, 1.0]); + assert_eq!(&a + &b, P(vec![1.0, 0.0, 0.0, 1.0])); + } + + #[test] + fn sub_test() { + let a = P(vec![1.0, 2.0, 3.0]); + let b = P(vec![1.0]); + assert_eq!(&a - &b, P(vec![0.0, 2.0, 3.0])); + } + #[test] fn poly_is_zero() { let p = vec![0.0; 5]; -- cgit v1.2.3