Last active
April 17, 2021 15:38
-
-
Save pertsevds/ee50decaff60f77421c65a79f7092183 to your computer and use it in GitHub Desktop.
Rectangles intersection C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace Rectangles | |
{ | |
public static class RectanglesTask | |
{ | |
// Пересекаются ли два прямоугольника (пересечение только по границе также считается пересечением) | |
public static bool AreIntersected(Rectangle r1, Rectangle r2) | |
{ | |
return !(r1.Left > r2.Right || r2.Left > r1.Right || r1.Bottom < r2.Top || r2.Bottom < r1.Top); | |
} | |
// Площадь пересечения прямоугольников | |
public static int IntersectionSquare(Rectangle r1, Rectangle r2) | |
{ | |
if (AreIntersected(r1, r2)) | |
return (Math.Min(r1.Right, r2.Right) - Math.Max(r1.Left, r2.Left)) * | |
(Math.Min(r1.Bottom, r2.Bottom) - Math.Max(r1.Top, r2.Top)); | |
return 0; | |
} | |
// Если один из прямоугольников целиком находится внутри другого — вернуть номер (с нуля) внутреннего. | |
// Иначе вернуть -1 | |
// Если прямоугольники совпадают, можно вернуть номер любого из них. | |
public static int IndexOfInnerRectangle(Rectangle r1, Rectangle r2) | |
{ | |
if (IsInner(r1, r2)) | |
return 0; | |
if (IsInner(r2, r1)) | |
return 1; | |
return -1; | |
} | |
private static bool IsInner(Rectangle r1, Rectangle r2) | |
{ | |
return r1.Bottom <= r2.Bottom && r1.Right <= r2.Right && r1.Top >= r2.Top && r1.Left >= r2.Left; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment