Skip to content

Commit

Permalink
Merge 50b1bd2 into 50c6679
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Feb 27, 2019
2 parents 50c6679 + 50b1bd2 commit 1b2874c
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,4 +197,5 @@ problems from
* [Day 184](https://github.com/vaskoz/dailycodingproblem-go/issues/378)
* [Day 185](https://github.com/vaskoz/dailycodingproblem-go/issues/381)
* [Day 186](https://github.com/vaskoz/dailycodingproblem-go/issues/382)
* [Day 187](https://github.com/vaskoz/dailycodingproblem-go/issues/387)
* [Day 188](https://github.com/vaskoz/dailycodingproblem-go/issues/388)
32 changes: 32 additions & 0 deletions day187/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package day187

// Rectangle is a representation of a rectangle.
type Rectangle struct {
TopLeftX, TopLeftY int
Width, Height int
}

// DoesRectanglePairOverlap returns true if any rectangles
// overlap.
// Runs in O(N^2) time.
func DoesRectanglePairOverlap(rects []Rectangle) bool {
for i, left := range rects {
for j, right := range rects {
if j > i {
if left.TopLeftX > right.TopLeftX {
left, right = right, left
}
if right.TopLeftX < left.TopLeftX+left.Width {
up, dn := left, right
if up.TopLeftY < dn.TopLeftY {
up, dn = dn, up
}
if dn.TopLeftY > up.TopLeftY-up.Height {
return true
}
}
}
}
}
return false
}
32 changes: 32 additions & 0 deletions day187/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package day187

import "testing"

var testcases = []struct {
rects []Rectangle
expected bool
}{
{[]Rectangle{{1, 4, 3, 3}, {-1, 3, 2, 1}, {0, 5, 4, 3}}, true},
{[]Rectangle{{1, 4, 1, 1}, {-1, 3, 1, 1}, {0, 5, 4, 3}}, false},
{[]Rectangle{{1, 1, 1, 1}, {2, 2, 1, 1}, {3, 3, 1, 1}}, false},
{[]Rectangle{{1, 1, 2, 1}, {2, 2, 1, 2}, {3, 3, 1, 1}}, true},
{[]Rectangle{{0, 9, 1, 1}, {1, 1, 1, 1}, {2, 2, 1, 1}, {0, 10, 2, 2}}, true},
{[]Rectangle{{1, 1, 1, 1}, {2, 2, 1, 1}, {0, 10, 2, 2}}, false},
}

func TestDoesRectanglePairOverlap(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := DoesRectanglePairOverlap(tc.rects); result != tc.expected {
t.Errorf("Given %v, expected %v, got %v", tc.rects, tc.expected, result)
}
}
}

func BenchmarkDoesRectanglePairOverlap(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
DoesRectanglePairOverlap(tc.rects)
}
}
}

0 comments on commit 1b2874c

Please sign in to comment.