Skip to content

Commit 6f6d1de

Browse files
committed
feat(day 111): compute next ball position with wall bounce logic
1 parent f7a1a6e commit 6f6d1de

1 file changed

Lines changed: 75 additions & 0 deletions

File tree

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
"""
2+
3+
Ball Trajectory
4+
Today's challenge is inspired by the video game Pong, which was released November 29, 1972.
5+
6+
Given a matrix (array of arrays) that includes the location of the ball (2), and the previous location of the ball (1), return the matrix indices for the next location of the ball.
7+
8+
The ball always moves in a straight line.
9+
The movement direction is determined by how the ball moved from 1 to 2.
10+
The edges of the matrix are considered walls. If the balls hits a:
11+
top or bottom wall, it bounces by reversing its vertical direction.
12+
left or right wall, it bounces by reversing its horizontal direction.
13+
corner, it bounces by reversing both directions.
14+
"""
15+
import unittest
16+
17+
class BallTrajectoryTest(unittest.TestCase):
18+
19+
def test1(self):
20+
self.assertEqual(get_next_location([[0,0,0,0], [0,0,0,0], [0,1,2,0], [0,0,0,0]]),[2, 3])
21+
22+
def test2(self):
23+
self.assertEqual(get_next_location([[0,0,0,0], [0,0,1,0], [0,2,0,0], [0,0,0,0]]),[3, 0])
24+
25+
def test3(self):
26+
self.assertEqual(get_next_location([[0,2,0,0], [1,0,0,0], [0,0,0,0], [0,0,0,0]]),[1, 2])
27+
28+
def test4(self):
29+
self.assertEqual(get_next_location([[0,0,0,0], [0,0,0,0], [2,0,0,0], [0,1,0,0]]),[1, 1])
30+
31+
def test5(self):
32+
self.assertEqual(get_next_location([[0,0,0,0], [0,0,0,0], [0,0,1,0], [0,0,0,2]]),[2, 2])
33+
34+
35+
36+
def get_next_location(matrix):
37+
38+
rows, cols = len(matrix), len(matrix[0])
39+
40+
# Find positions of 1 and 2
41+
42+
prev = None
43+
curr = None
44+
45+
for r in range(rows):
46+
for c in range(cols):
47+
if matrix[r][c] == 1:
48+
prev = [r, c]
49+
elif matrix[r][c] == 2:
50+
curr = [r, c]
51+
52+
# Direction Vector
53+
dr = curr[0] - prev[0]
54+
dc = curr[1] - prev[1]
55+
56+
57+
# Next position
58+
nr, nc = curr[0] + dr, curr[1] + dc
59+
60+
if nr < 0 or nr >= rows: # vertical bounce
61+
62+
dr *= -1
63+
nr = curr[0] + dr
64+
65+
if nc < 0 or nc >= cols: # Horizontal bounce
66+
67+
dc *= -1
68+
nc = curr[1] + dc
69+
70+
return [nr, nc]
71+
72+
73+
if __name__ == "__main__":
74+
print(get_next_location([[0,0,0,0], [0,0,1,0], [0,2,0,0], [0,0,0,0]]))
75+
unittest.main()

0 commit comments

Comments
 (0)