Skip to content

Commit

Permalink
Merge pull request #384 from vaskoz/day185
Browse files Browse the repository at this point in the history
Day185
  • Loading branch information
vaskoz committed Feb 24, 2019
2 parents 646f31b + 525d2fb commit a4d035a
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
39 changes: 39 additions & 0 deletions day185/problem.go
Original file line number Diff line number Diff line change
@@ -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
}
29 changes: 29 additions & 0 deletions day185/problem_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}

0 comments on commit a4d035a

Please sign in to comment.