Skip to content

Commit 907b08f

Browse files
Advent of Code 2024 - Day 5 : Python version (#50)
1 parent 0a93acb commit 907b08f

File tree

2 files changed

+90
-0
lines changed

2 files changed

+90
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
2+
dirs = [
3+
[-1, -1],
4+
[-1, 0],
5+
[-1, 1],
6+
[0, -1],
7+
[0, 1],
8+
[1, -1],
9+
[1, 0],
10+
[1, 1]
11+
]
12+
13+
14+
def solve_day4_part1(grid):
15+
res = 0
16+
row, column = len(grid), len(grid[0])
17+
18+
for i in range(row):
19+
for j in range(column):
20+
if grid[i][j] == '.':
21+
continue
22+
roll_cnt = 0
23+
for dir in dirs:
24+
x, y = i+dir[0], j+dir[1]
25+
if x < 0 or x > row-1 or y < 0 or y > column-1:
26+
continue
27+
if grid[x][y] == '@':
28+
roll_cnt += 1
29+
30+
if roll_cnt < 4:
31+
res += 1
32+
33+
return res
34+
35+
36+
def solve_day4_part2(grid):
37+
res = 0
38+
row, column = len(grid), len(grid[0])
39+
40+
while True:
41+
is_roll_moved = False
42+
for i in range(row):
43+
for j in range(column):
44+
if grid[i][j] == '.':
45+
continue
46+
roll_cnt = 0
47+
for dir in dirs:
48+
x, y = i+dir[0], j+dir[1]
49+
if x < 0 or x > row-1 or y < 0 or y > column-1:
50+
continue
51+
if grid[x][y] == '@':
52+
roll_cnt += 1
53+
54+
if roll_cnt < 4:
55+
is_roll_moved = True
56+
grid[i] = grid[i][:j]+'.'+grid[i][j+1:]
57+
res += 1
58+
59+
if not is_roll_moved:
60+
break
61+
return res
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import unittest
2+
3+
from day4 import solve_day4_part1, solve_day4_part2
4+
5+
question_input = [
6+
"..@@.@@@@.",
7+
"@@@.@.@.@@",
8+
"@@@@@.@.@@",
9+
"@.@@@@..@.",
10+
"@@.@@@@.@@",
11+
".@@@@@@@.@",
12+
".@.@.@.@@@",
13+
"@.@@@.@@@@",
14+
".@@@@@@@@.",
15+
"@.@.@@@.@.",
16+
]
17+
18+
19+
class TestSample(unittest.TestCase):
20+
21+
def test_part1(self):
22+
self.assertEqual(solve_day4_part1(question_input), 13)
23+
24+
def test_part2(self):
25+
self.assertEqual(solve_day4_part2(question_input), 43)
26+
27+
28+
if __name__ == "__main__":
29+
unittest.main()

0 commit comments

Comments
 (0)