2024 Day 4

This commit is contained in:
2024-12-09 13:49:55 +00:00
parent d81a288185
commit 3f40993d2b
2 changed files with 96 additions and 0 deletions

40
2024/Day-04/day04-1.py Normal file
View File

@@ -0,0 +1,40 @@
#!/usr/bin/python3
def look_around(coords: tuple, direction: tuple):
global found
letters = ['X','M','A','S']
orig_x = coords[0]
orig_y = coords[1]
x_to_check = direction[0]
y_to_check = direction[1]
try:
next_letter = letters[letters.index(wordsearch[orig_y][orig_x]) + 1]
except IndexError:
found += 1
return
for diff_x in x_to_check:
for diff_y in y_to_check:
x = orig_x + diff_x
y = orig_y + diff_y
if x < 0 or y < 0:
continue
try:
if wordsearch[y][x] == next_letter:
look_around((x, y), ([diff_x], [diff_y]))
except IndexError:
pass
if __name__ == '__main__':
found = 0
with open('input.txt', 'r') as input_file:
wordsearch = [list(x.strip()) for x in input_file.readlines()]
for y in range(len(wordsearch)):
for x in range(len(wordsearch[y])):
if wordsearch[y][x] != 'X':
continue
res = look_around((x,y), ([-1,0,1],[-1,0,1]))
if res:
found += 1
print(found)

56
2024/Day-04/day04-2.py Normal file
View File

@@ -0,0 +1,56 @@
#!/usr/bin/python3
def look_around(coords: tuple, direction: tuple):
letters = ['M','S']
orig_x = coords[0]
orig_y = coords[1]
x_to_check = direction[0]
y_to_check = direction[1]
letters_found = {}
for diff_x in x_to_check:
for diff_y in y_to_check:
x = orig_x + diff_x
letters_found[x] = letters_found.get(x, [])
y = orig_y + diff_y
if x < 0 or y < 0:
continue
try:
if wordsearch[y][x] in letters:
letters_found[x].append(wordsearch[y][x])
except IndexError:
pass
letters_found = list(letters_found.values())
success = 0
if any([len(x) < 2 for x in letters_found]):
return False
match letters_found[0][0]:
case 'M':
if letters_found[1][1] == 'S':
success += 1
case 'S':
if letters_found[1][1] == 'M':
success += 1
match letters_found[0][1]:
case 'M':
if letters_found[1][0] == 'S':
success += 1
case 'S':
if letters_found[1][0] == 'M':
success += 1
if success == 2:
return True
return False
if __name__ == '__main__':
found = 0
with open('input.txt', 'r') as input_file:
wordsearch = [list(x.strip()) for x in input_file.readlines()]
for y in range(len(wordsearch)):
for x in range(len(wordsearch[y])):
if wordsearch[y][x] != 'A':
continue
if look_around((x,y), ([-1,1],[-1,1])):
found += 1
print(found)