using System; using System.Collections.Generic; using System.Linq; public class Rectangle{ // simulate the missing System.Drawing namespace under mono public int X; public int Y; public int Width; public int Height; public bool IntersectsWith(Rectangle rect) { return rect.X < this.X + this.Width && this.X < rect.X + rect.Width && rect.Y < this.Y + this.Height && this.Y < rect.Y + rect.Height; } } public class Test { private static Rectangle getRandomRectangle(Random rnd) { var rect = new Rectangle(); rect.X = rnd.Next(0, 1000); rect.Y = rnd.Next(0, 1000); rect.Width = rnd.Next(1, 200); rect.Height = rnd.Next(1, 200); return rect; } public static void Main() { // sample data var rectangles = new List(); var rnd = new Random(); for (int i = 0; i < 100; i++) rectangles.Add(getRandomRectangle(rnd)); // main algorithm var intersectingRectangles = new List>(); HashSet alreadyChecked = new HashSet(); var toCheck = rectangles.Except(alreadyChecked); while (alreadyChecked.Count != rectangles.Count) { var intersections = toCheck.Where(r => r.IntersectsWith(toCheck.ElementAt(0))) .ToList(); intersectingRectangles.Add(intersections); foreach (var r in intersections) alreadyChecked.Add(r); } intersectingRectangles.Sort((rl1, rl2) => (-1) * rl1.Count.CompareTo(rl2.Count)); // just output the result Console.WriteLine("Total count:{0}", intersectingRectangles.Count); foreach (var irec in intersectingRectangles) Console.WriteLine("Count => {0} Rectangles => {1}" , irec.Count , String.Join(",", irec.Select(r => String.Format("[{0};{1};{2};{3}]" , r.X, r.Y, r.Width, r.Height)).ToArray())); } }