Ceres Search [Day 4 - Advent of Code 2024 - Python]

preview_player
Показать описание
I am given a large block of text containing a bunch of X, M, A, and S. In part 1, I have to find every instance of the word XMAS and return the count. In part 2, I need to search for places where two instances of the word MAS are crossed at the A, like:
M S
A
M S

I'll start by creating sets for each of the letters with all the points they are located at, which is a nice mapping to work with. In part 2, I'll use some lambda functions as helpers to make the checks more intuitive.

[00:00] Part1 introduction
[00:46] Setup / data overview
[01:27] Making char_map
[02:37] Counting XMAS
[05:54] Solving part 1
[06:25] Slight part 1 improvement
[06:52] Part 2 challenge
[07:29] Start counting X-MAS
[08:01] Creating helper functions
[09:38] Counting X-MAS
[11:42] Solving part 2
[11:53] Conclusion

#adventofcode #python
Рекомендации по теме
Комментарии
Автор

Clean and great code, but would love a bit of explanation about the thought process about the approach. Cheers

santosh
Автор

I did a bit of a refactor for part 2, removed lambdas and used functions and returned booleans for the checks

```
def up_left(row, c): return r - 1, c - 1
def up_right(r, c): return r - 1, c + 1
def down_left(r, c): return r + 1, c - 1
def down_right(r, c): return r + 1, c + 1

def check_up_left(r, c):
if down_left(r, c) in char_map["M"] and up_right(r, c) in char_map["S"] and down_right(r, c) in char_map["S"]:
return True
elif up_right(r, c) in char_map["M"] and down_left(r, c) in char_map["S"] and down_right(r, c) in char_map["S"]:
return True
return False

def check_down_right(r, c):
if down_left(r, c) in char_map["M"] and up_right(r, c) in char_map["S"] and up_left(r, c) in char_map["S"]:
return True
elif up_right(r, c) in char_map["M"] and down_left(r, c) in char_map["S"] and up_left(r, c) in char_map["S"]:
return True
return False

part2 = 0
for r, c in char_map["A"]:
if up_left(r, c) in char_map["M"] and check_up_left(r, c):
part2 += 1
elif down_right(r, c) in char_map["M"] and check_down_right(r, c):
part2 += 1
print(part2)
```

BenjaminKane-rs
join shbcf.ru