Advertisement
_andrea_

Untitled

Jul 10th, 2022 (edited)
1,239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.42 KB | None | 0 0
  1. pub enum Product {
  2.     Number(i32),
  3.     Product(Box<Product>, Box<Product>),
  4. }
  5.  
  6. impl Product {
  7.     pub fn sign(&self) -> i32 {
  8.         match self {
  9.             Product::Number(n) => n.signum(),
  10.             Product::Product(p1, p2) => {
  11.                 let s1 = p1.sign();
  12.                 if s1 == 1 {
  13.                     p2.sign()
  14.                 } else {
  15.                     -p2.sign()
  16.                 }
  17.             }
  18.         }
  19.     }
  20. }
  21.  
  22.  
  23.  
  24. struct ChainedProduct {
  25.     value: i32,
  26.     next: Option<Box<ChainedProduct>>,
  27. }
  28.  
  29.  
  30. impl ChainedProduct {
  31.     pub fn new(values: &[i32]) -> ChainedProduct {
  32.         assert!(!values.is_empty());
  33.         ChainedProduct {
  34.             value: values[0],
  35.             next: if values.len() > 1 {
  36.                 Some(Box::new(ChainedProduct::new(&values[1..])))
  37.             } else {
  38.                 None
  39.             },
  40.         }
  41.     }
  42.     pub fn sign(self) -> i32 {
  43.         if self.next.is_none() {
  44.             return self.value.signum();
  45.         }
  46.         if self.value.signum() == 1 {
  47.             self.next.unwrap().sign()
  48.         } else {
  49.             -self.next.unwrap().sign()
  50.         }
  51.     }
  52. }
  53.  
  54. fn main() {
  55.     let p = Product::new(-1, Product::new(2, Product::new(-3, Product::new(1, Product::new(-2, Product::new(-3, -4))))));
  56.     println!("{}", p.sign());
  57.     let cp = ChainedProduct::new(&[-1, 2, -3, 1, -2, -3, -4]);
  58.     println!("{}", cp.sign());
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement