Skip to content

Instantly share code, notes, and snippets.

@elliz
Last active January 14, 2022 01:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elliz/9d7da1fa74a76d84be4600dcbc121bd6 to your computer and use it in GitHub Desktop.
Save elliz/9d7da1fa74a76d84be4600dcbc121bd6 to your computer and use it in GitHub Desktop.
Polygon Area Tests
// Testing code via Stack Overflow answer at:
// https://stackoverflow.com/a/16281192/581414
void Main()
{
var square = new List<Point>{
new Point(1, 1),
new Point(1, 10),
new Point(10,10),
new Point(10,1),
};
square.Area().Dump("Square 9x9 => area should be 81");
square.Add(new Point(1, 1)); // close polygon
square.Area().Dump("Square 9x9 => area should be 81");
var triangle = new List<Point>{
new Point(1, 1),
new Point(1, 10),
new Point(10,10),
};
triangle.Area().Dump("Right-angled triangle => area should be 81/2 = 40.5");
triangle.Add(new Point(1, 1)); // close polygon
triangle.Area().Dump("Right-angled triangle => area should be 81/2 = 40.5");
}
public static class ExtensionMethods {
public static double Area(this List<Point> points)
{
return Math.Abs(points.Take(points.Count - 1)
.Select((p, i) => (points[i + 1].X - p.X) * (points[i + 1].Y + p.Y))
.Sum() / 2);
}
}
public class Point
{
public List<double> Coordinates {get; set;} = new();
public Point (double x, double y)
{
Coordinates.Add(x);
Coordinates.Add(y);
}
public double X {get { return Coordinates[0]; }}
public double Y {get { return Coordinates[1]; }}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment