Skip to content

Commit

Permalink
Add area of a polygon defined by a vector of points (#531)
Browse files Browse the repository at this point in the history
  • Loading branch information
Gyan172004 authored Oct 2, 2023
1 parent eaa3323 commit 66d6d52
Showing 1 changed file with 94 additions and 0 deletions.
94 changes: 94 additions & 0 deletions src/math/area_of_polygon.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/**
* @file
* @brief Calculate the area of a polygon defined by a vector of points.
*
* @details
* This program provides a function to calculate the area of a polygon defined by a vector of points.
* The area is calculated using the formula: A = |Σ((xi - xi-1) * (yi + yi-1))| / 2
* where (xi, yi) are the coordinates of the points in the vector.
*
* @param fig A vector of points defining the polygon.
* @return The area of the polygon.
*
* @author [Gyandeep](https://github.com/Gyan172004)
* @see [Wikipedia - Polygon](https://en.wikipedia.org/wiki/Polygon)
*/

struct Point {
x: f64,
y: f64,
}

/**
* Calculate the area of a polygon defined by a vector of points.
* @param fig A vector of points defining the polygon.
* @return The area of the polygon.
*/

fn area(fig: &Vec<Point>) -> f64 {
let mut res = 0.0;

for i in 0..fig.len() {
let p = if i > 0 {
&fig[i - 1]
} else {
&fig[fig.len() - 1]
};
let q = &fig[i];

res += (p.x - q.x) * (p.y + q.y);
}

f64::abs(res) / 2.0
}

#[cfg(test)]
mod tests {
use super::*;

/**
* Test case for calculating the area of a triangle.
*/
#[test]
fn test_area_triangle() {
let points = vec![
Point { x: 0.0, y: 0.0 },
Point { x: 1.0, y: 0.0 },
Point { x: 0.0, y: 1.0 },
];

assert_eq!(area(&points), 0.5);
}

/**
* Test case for calculating the area of a square.
*/
#[test]
fn test_area_square() {
let points = vec![
Point { x: 0.0, y: 0.0 },
Point { x: 1.0, y: 0.0 },
Point { x: 1.0, y: 1.0 },
Point { x: 0.0, y: 1.0 },
];

assert_eq!(area(&points), 1.0);
}

/**
* Test case for calculating the area of a hexagon.
*/
#[test]
fn test_area_hexagon() {
let points = vec![
Point { x: 0.0, y: 0.0 },
Point { x: 1.0, y: 0.0 },
Point { x: 1.5, y: 0.866 },
Point { x: 1.0, y: 1.732 },
Point { x: 0.0, y: 1.732 },
Point { x: -0.5, y: 0.866 },
];

assert_eq!(area(&points), 2.598);
}
}

0 comments on commit 66d6d52

Please sign in to comment.