Last active
August 29, 2015 14:22
-
-
Save VegaFromLyra/5ddd7f25c116de84b6cf to your computer and use it in GitHub Desktop.
Overlapping rectangles
This file contains 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; | |
using System.Collections.Generic; | |
// https://www.interviewcake.com/question/rectangular-love | |
// Find overlap between 2 rectangles | |
namespace intersectionRectangles | |
{ | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
var rectangle1 = new Dictionary<string, int>(); | |
rectangle1.Add("x", 5); | |
rectangle1.Add("y", 1); | |
rectangle1.Add("width", 2); | |
rectangle1.Add("height", 4); | |
var rectangle2 = new Dictionary<string, int>(); | |
rectangle2.Add("x", 3); | |
rectangle2.Add("y", 4); | |
rectangle2.Add("width", 5); | |
rectangle2.Add("height", 3); | |
var overlap = findOverlap(rectangle1, rectangle2); | |
if (overlap == null) { | |
Console.WriteLine("No overlap found!"); | |
} else { | |
Console.WriteLine("x: {0}", overlap["x"]); | |
Console.WriteLine("y: {0}", overlap["y"]); | |
Console.WriteLine("Width: {0}", overlap["width"]); | |
Console.WriteLine("Height: {0}", overlap["height"]); | |
} | |
} | |
static Dictionary<string, int> findOverlap(int point1, int length1, int point2, int length2, string pointKey, string lengthKey) { | |
int highestStartPoint = Math.Max(point1, point2); | |
int lowestEndPoint = Math.Min(point1 + length1, point2 + length2); | |
if (lowestEndPoint <= highestStartPoint) { | |
return null; | |
} | |
var overlap = new Dictionary<string, int>(); | |
overlap.Add(pointKey, highestStartPoint); | |
overlap.Add(lengthKey, lowestEndPoint - highestStartPoint); | |
return overlap; | |
} | |
static Dictionary<string, int> findOverlap(Dictionary<string, int> r1, Dictionary<string, int> r2) { | |
var xOverlap = findOverlap(r1["x"], r1["width"], r2["x"], r2["width"], "x", "width"); | |
var yOverlap = findOverlap(r1["y"], r1["height"], r2["y"], r2["height"], "y", "height"); | |
if (xOverlap == null || yOverlap == null) { | |
return null; | |
} | |
var overlap = new Dictionary<string, int>(); | |
overlap.Add("x", xOverlap["x"]); | |
overlap.Add("y", yOverlap["y"]); | |
overlap.Add("width", xOverlap["width"]); | |
overlap.Add("height", yOverlap["height"]); | |
return overlap; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment