using System; using System.Collections; using System.Collections.Generic; using System.Linq; public static class Program { public static void Main() { var samples = new Dictionary { { "a", new Polygon { { -5, 1 }, { -3, 3 }, { -1, 5 }, { 1, 5 }, { 3, 3 }, { 5, 1 }, { 5, -1 }, { 3, -3 }, { 1, -5 }, { -1, -5 }, { -3, -3 }, { -5, -1 }, } }, { "b", new Polygon { { -3, 0 }, { 0, 3 }, { 3, 0 }, { 0, -3 }, } }, { "c", new Polygon { { 4, 0 }, { 7, 3 }, { 10, 0 }, { 7, -3 }, } } }; foreach (var p1 in samples) foreach (var p2 in samples) { var result = IsPolygonsIntersecting(p1.Value, p2.Value); Console.WriteLine("IsPolygonsIntersecting({0}, {1}) = {2}", p1.Key, p2.Key, result); } } static bool IsPolygonsIntersecting(Polygon a, Polygon b) { foreach (var polygon in new[] { a, b }) { for (int i1 = 0; i1 < polygon.Points.Count; i1++) { int i2 = (i1 + 1) % polygon.Points.Count; var p1 = polygon.Points[i1]; var p2 = polygon.Points[i2]; var normal = new Point(p2.Y - p1.Y, p1.X - p2.X); double? minA = null, maxA = null; foreach (var p in a.Points) { var projected = normal.X * p.X + normal.Y * p.Y; if (minA == null || projected < minA) minA = projected; if (maxA == null || projected > maxA) maxA = projected; } double? minB = null, maxB = null; foreach (var p in b.Points) { var projected = normal.X * p.X + normal.Y * p.Y; if (minB == null || projected < minB) minB = projected; if (maxB == null || projected > maxB) maxB = projected; } if (maxA < minB || maxB < minA) return false; } } return true; } } class Polygon : IEnumerable { public List Points { get; set; } public Polygon() : this(new Point[0]) { } public Polygon(IEnumerable points) { this.Points = points.ToList(); } public IEnumerator GetEnumerator() { return Points.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } public void Add(Point p) { this.Points.Add(p); } public void Add(double x, double y) { this.Add(new Point(x, y)); } } class Point { public double X { get; set; } public double Y { get; set; } public Point(double x = 0, double y = 0) { this.X = x; this.Y = y; } }