Polygon Struct
우리는 몇개의 꼭지점을 가진 다각형
을 표현하는 구조체를 만들 것입니다.
아래 코드를 https://play.rust-lang.org/에 복사해서 테스트가 통과하도록 빠진 메서드를 구현하시면 됩니다:
We will create a
Polygon
struct which contain some points. Copy the code below to https://play.rust-lang.org/ and fill in the missing methods to make the tests pass:
// TODO: remove this when you're done with your implementation. #![allow(unused_variables, dead_code)] pub struct Point { // add fields } impl Point { // add methods } pub struct Polygon { // add fields } impl Polygon { // add methods } pub struct Circle { // add fields } impl Circle { // add methods } pub enum Shape { Polygon(Polygon), Circle(Circle), } #[cfg(test)] mod tests { use super::*; fn round_two_digits(x: f64) -> f64 { (x * 100.0).round() / 100.0 } #[test] fn test_point_magnitude() { let p1 = Point::new(12, 13); assert_eq!(round_two_digits(p1.magnitude()), 17.69); } #[test] fn test_point_dist() { let p1 = Point::new(10, 10); let p2 = Point::new(14, 13); assert_eq!(round_two_digits(p1.dist(p2)), 5.00); } #[test] fn test_point_add() { let p1 = Point::new(16, 16); let p2 = p1 + Point::new(-4, 3); assert_eq!(p2, Point::new(12, 19)); } #[test] fn test_polygon_left_most_point() { let p1 = Point::new(12, 13); let p2 = Point::new(16, 16); let mut poly = Polygon::new(); poly.add_point(p1); poly.add_point(p2); assert_eq!(poly.left_most_point(), Some(p1)); } #[test] fn test_polygon_iter() { let p1 = Point::new(12, 13); let p2 = Point::new(16, 16); let mut poly = Polygon::new(); poly.add_point(p1); poly.add_point(p2); let points = poly.iter().cloned().collect::<Vec<_>>(); assert_eq!(points, vec![Point::new(12, 13), Point::new(16, 16)]); } #[test] fn test_shape_circumferences() { let mut poly = Polygon::new(); poly.add_point(Point::new(12, 13)); poly.add_point(Point::new(17, 11)); poly.add_point(Point::new(16, 16)); let shapes = vec![ Shape::from(poly), Shape::from(Circle::new(Point::new(10, 20), 5)), ]; let circumferences = shapes .iter() .map(Shape::circumference) .map(round_two_digits) .collect::<Vec<_>>(); assert_eq!(circumferences, vec![15.48, 31.42]); } } #[allow(dead_code)] fn main() {}
역주
- 구현체의 +(Add), -(Sub)까지 구현하게 만들었는데 난이도가 꽤 높습니다
- shape와 관련된 impl도 구현해야합니다.
- 일단 실행해서 컴파일러 오류를 잡아가는 TDD로 진행해야 그나마(…) 수월하네요
힌트- 포인트 연산 함수, shape from 함수
#![allow(unused)] fn main() { impl std::ops::Add for Point { type Output = Self; fn add(self, other: Self) -> Self::Output { Self { x: self.x + other.x, y: self.y + other.y, } } } impl std::ops::Sub for Point { type Output = Self; fn sub(self, other: Self) -> Self::Output { Self { x: self.x - other.x, y: self.y - other.y, } } } impl From<Polygon> for Shape { fn from(poly: Polygon) -> Self { Shape::Polygon(poly) } } impl From<Circle> for Shape { fn from(circle: Circle) -> Self { Shape::Circle(circle) } } }
힌트- 구현함수 설명
- point.magnitude : (0,0)과 point의 거리
- point.dist: 입력받은 포인트와 point 사이의 거리
- shape.circumference: 테두리 길이(다각형), 둘레(원)