Demo entry 6785328

Rectangle and Quadrilaterals

   

Submitted by anonymous on Mar 15, 2019 at 06:10
Language: Rust. Code size: 1.2 kB.

struct Point {
  x: f64,
  y: f64
}

impl Point {
  fn origin() -> Self {
    Point { x: 0.0, y: 0.0 }
  }
  
  fn distance(&self, p2: Point) -> f64 {
    let Point { x: x2, y: y2 } = p2;
    ((x2 - self.x).powf(2.0) + (y2 - self.y).powf(2.0)).sqrt()
  }
}

struct Rectangle {
    /// This needs the opposite points
    /// ---> *-------*
    ///      |       |
    ///      |       |
    ///      *-------* <---
    p1: Point,
    p2: Point
}

impl Rectangle {
  fn create(length: f64, height: f64) -> Self {
    // Creates a rectangle from the origin
    
    Rectangle {
      p1: Point { x: 0.0, y: height },
      p2: Point { x: length, y: 0.0 }
    }
  } 

  fn get_height_and_length(&self) -> (f64, f64) {
    let Point { x: x1, y: y1 } = self.p1;
    let Point { x: x2, y: y2 } = self.p2;
    
    (
      (x2 - x1).abs(),
      (y2 - y1).abs()
    )
  }
  
  fn area(&self) -> f64 {
    let (height, length) = self.get_height_and_length();
    
    height * length
  }
  
  fn perimeter(&self) -> f64 {
    let (height, length) = self.get_height_and_length();
    
    2 * (height + length)
  }
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).