Repository: vaskoz/dailycodingproblem-go (go)

Issue:
Day 185
Good morning! Here's your coding interview problem for today.

This problem was asked by Google.

Given two rectangles on a 2D graph, return the area of their intersection. If the rectangles don't intersect, return 0.

For example, given the following rectangles:
```
{
    "top_left": (1, 4),
    "dimensions": (3, 3) # width, height
}
```
and
```
{
    "top_left": (0, 5),
    "dimensions" (4, 3) # width, height
}
```
return 6.

Pull request description:
Day185
Resolves #381.

Patch:
diff --git a/README.md b/README.md
index b4413fb..b2a2680 100644
--- a/README.md
+++ b/README.md
@@ -194,3 +194,4 @@ problems from
 * [Day 181](https://github.com/vaskoz/dailycodingproblem-go/issues/375)
 * [Day 182](https://github.com/vaskoz/dailycodingproblem-go/issues/376)
 * [Day 184](https://github.com/vaskoz/dailycodingproblem-go/issues/378)
+* [Day 185](https://github.com/vaskoz/dailycodingproblem-go/issues/381)
diff --git a/day185/problem.go b/day185/problem.go
new file mode 100644
index 0000000..5e38191
--- /dev/null
+++ b/day185/problem.go
@@ -0,0 +1,39 @@
+package day185
+
+// Rectangle with a top-left coordinate plus width and height.
+type Rectangle struct {
+	topLeftX, topLeftY int
+	width, height      int
+}
+
+// AreaOfIntersection returns the area of intersection of two
+// rectangles.
+func AreaOfIntersection(r1, r2 Rectangle) int {
+	leftMostR := r1
+	rightMostR := r2
+	if r2.topLeftX < r1.topLeftX {
+		leftMostR = r2
+		rightMostR = r1
+	}
+	deltaX := 0
+	if leftMostRR := leftMostR.topLeftX + leftMostR.width; leftMostRR > rightMostR.topLeftX {
+		deltaX = leftMostRR - rightMostR.topLeftX
+	}
+	if deltaX == 0 {
+		return 0
+	}
+	topMostR := r1
+	bottomMostR := r2
+	if r2.topLeftY < r1.topLeftY {
+		topMostR = r2
+		bottomMostR = r1
+	}
+	deltaY := 0
+	if topMostRR := topMostR.topLeftY + topMostR.height; topMostRR > bottomMostR.topLeftY {
+		deltaY = topMostRR - bottomMostR.topLeftY
+	}
+	if deltaY == 0 {
+		return 0
+	}
+	return deltaX * deltaY
+}


Test patch:
diff --git a/day185/problem_test.go b/day185/problem_test.go
new file mode 100644
index 0000000..c32c101
--- /dev/null
+++ b/day185/problem_test.go
@@ -0,0 +1,29 @@
+package day185
+
+import "testing"
+
+var testcases = []struct {
+	r1, r2 Rectangle
+	area   int
+}{
+	{Rectangle{1, 4, 3, 3}, Rectangle{0, 5, 4, 3}, 6},
+	{Rectangle{10, 10, 3, 3}, Rectangle{0, 0, 3, 3}, 0},
+	{Rectangle{10, 10, 3, 3}, Rectangle{10, 0, 3, 3}, 0},
+}
+
+func TestAreaOfIntersection(t *testing.T) {
+	t.Parallel()
+	for _, tc := range testcases {
+		if area := AreaOfIntersection(tc.r1, tc.r2); area != tc.area {
+			t.Errorf("Expected %v, got %v", tc.area, area)
+		}
+	}
+}
+
+func BenchmarkAreaOfIntersection(b *testing.B) {
+	for i := 0; i < b.N; i++ {
+		for _, tc := range testcases {
+			AreaOfIntersection(tc.r1, tc.r2)
+		}
+	}
+}