Skip to content

Commit 95035e7

Browse files
author
Mauricio Klein
committed
Add solution for challenge #35
1 parent eadfdec commit 95035e7

File tree

6 files changed

+89
-0
lines changed

6 files changed

+89
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,4 @@
3434
- [x] [Challenge 32: Shortest path in a indirected acyclic graph](challenge-32/)
3535
- [x] [Challenge 33: Merge Overlapping Intervals](challenge-33/)
3636
- [x] [Challenge 34: Subset sum problem](challenge-34/)
37+
- [x] [Challenge 35: Count rectangles](challenge-35/)

challenge-35/Makefile

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
test:
2+
python test_*.py
3+
4+
.PHONY: test

challenge-35/README.md

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# Count rectangles
2+
3+
## Description
4+
5+
Given a list of carthesian pairs (x, y), return the number of rectangles formed by these pairs.
6+
7+
## Example
8+
9+
```
10+
Input:[ (1,3), (1,4), (2,3), (2,4), (3,3), (3,4), (4,3), (4,4) ]
11+
Output: 4
12+
```

challenge-35/__init__.py

Whitespace-only changes.

challenge-35/solver.py

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#
2+
# Time complexity: O(n^2)
3+
# Space complexity: O(n/2) (worst case, where we've distinct vertical lines)
4+
#
5+
def count_rectangles(points):
6+
vertical_lines = {}
7+
8+
for p1 in points:
9+
for p2 in points:
10+
# Same points don't make a line
11+
if p1 == p2:
12+
continue
13+
14+
if stacked(p1, p2):
15+
point = make_point(p1, p2)
16+
vertical_lines[point] = vertical_lines.get(point, 0) + 1
17+
18+
acc = 0
19+
for count in vertical_lines.values():
20+
# We need at least two vertical lines to make a rectangle
21+
if count < 2:
22+
continue
23+
24+
acc += 1 if count == 2 else count
25+
26+
return acc
27+
28+
def make_point(p1, p2):
29+
p1_y, p2_y = p1[1], p2[1]
30+
31+
return (
32+
min(p1_y, p2_y),
33+
max(p1_y, p2_y)
34+
)
35+
36+
37+
def stacked(p1, p2):
38+
p1_x, p1_y = p1
39+
p2_x, p2_y = p2
40+
41+
if p1_x != p2_x:
42+
return False
43+
44+
return p1_y < p2_y

challenge-35/test_solver.py

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import unittest
2+
from solver import count_rectangles
3+
4+
class TestSolver(unittest.TestCase):
5+
def test_count_rectangles(self):
6+
points = [
7+
(1,3), (1,4), (2,3), (2,4)
8+
]
9+
10+
self.assertEqual(count_rectangles(points), 1)
11+
12+
def test_count_multiple_rectangles(self):
13+
points = [
14+
(1,3), (1,4), (2,3), (2,4),
15+
(2,1), (2,2), (3,1), (3,2)
16+
]
17+
18+
self.assertEqual(count_rectangles(points), 2)
19+
20+
def test_count_multiple_paralel_rectangles(self):
21+
points = [
22+
(1,3), (1,4), (2,3), (2,4), (3,3), (3,4), (4,3), (4,4)
23+
]
24+
25+
self.assertEqual(count_rectangles(points), 4)
26+
27+
if __name__ == "__main__":
28+
unittest.main()

0 commit comments

Comments
 (0)