From cb497e172fcb26dda42e45db793db1478db317bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Manuel=20Tom=C3=A1s?= Date: Mon, 11 Jan 2021 09:33:39 -0300 Subject: Implement mul for P --- src/poly.rs | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/src/poly.rs b/src/poly.rs index 34444b3..3f298cb 100644 --- a/src/poly.rs +++ b/src/poly.rs @@ -4,8 +4,8 @@ use crate::number::Number; use iter::Iter; use std::cmp; use std::cmp::Ordering; -use std::ops::{Add, Sub}; -use std::iter::{Zip, Take}; +use std::ops::{Add, Sub, Mul}; +use std::iter::{Sum, Zip, Take}; #[derive(PartialEq, Debug)] pub struct P(Vec); @@ -47,6 +47,24 @@ impl Sub for &P { } } +impl Mul for &P { + type Output = P; + + fn mul(self, other: Self) -> P { + let mut r = Vec::new(); + for i in 0..other.degree() + 1 { + let mut prefix = vec![0.0; i]; + let mut suffix: Vec = self.iter() + .take(self.degree() + 1) + .map(|x| {x * other.0[i]}) + .collect(); + prefix.append(&mut suffix); + r.push(P(prefix)); + } + r.iter().fold(P(vec![0.0]), |acc, x| &acc + x) + } +} + //****************************REFACTORING************************************ pub type Poly = Vec; @@ -134,6 +152,13 @@ pub fn gcd(a: &Poly, b: &Poly) -> Poly { mod tests { use super::*; + #[test] + fn mul_test() { + let a = P(vec![1.0, 2.0, 3.0]); + let b = P(vec![1.0, 2.0]); + assert_eq!(&a * &b, P(vec![1.0, 4.0, 7.0, 6.0])); + } + #[test] fn add_test() { let a = P(vec![1.0]); -- cgit v1.2.3