Skip to content

Instantly share code, notes, and snippets.

@qoda
Last active December 8, 2022 12:02
Show Gist options
  • Save qoda/1c5fad52aa237a4eaf6dca0f04d8fb94 to your computer and use it in GitHub Desktop.
Save qoda/1c5fad52aa237a4eaf6dca0f04d8fb94 to your computer and use it in GitHub Desktop.
AoC Day 8
from functools import reduce
from itertools import chain
def determine_visibility(input):
matrix = [[int(x) for x in b] for b in input]
def look_up(current_position):
x, y = current_position
return [matrix[i][x] for i in reversed(range(y))]
def look_down(current_position):
x, y = current_position
l = len(matrix[y])
return [matrix[i][x] for i in range(y + 1, l)]
def look_left(current_position):
x, y = current_position
return [matrix[y][i] for i in reversed(range(x))]
def look_right(current_position):
x, y = current_position
l = len(matrix[x])
return [matrix[y][i] for i in range(x + 1, l)]
direction_functions = [look_up, look_down, look_left, look_right]
matrix = [[int(x) for x in b] for b in input]
result_matrix1, result_matrix2 = [], []
for y, row in enumerate(matrix):
result_1, result_2 = [], []
for x, height in enumerate(row):
current_position = [x, y]
# Part 1
for direction_function in direction_functions:
direction_results = direction_function(current_position)
if all(map(lambda x: x < height, direction_results)):
result_1.append('x')
break
# Part 2
counters = []
for direction_function in direction_functions:
counter = 0
direction_results = direction_function(current_position)
for direction_result in direction_results:
counter += 1
if direction_result >= height:
break
counters.append(counter)
result_1.append(height)
result_2.append(reduce(lambda x, y: x * y, counters))
result_matrix1.append(result_1)
result_matrix2.append(result_2)
return (
len(
list(
chain(
*[list(filter(lambda x: x == 'x', i)) for i in result_matrix1]
)
)
),
max(list(chain(*result_matrix2)))
)
# Test 1
TEST_INPUT = ['30373', '25512', '65332', '33549', '35390']
assert determine_visibility(TEST_INPUT)[0] == 21
# Test 2
assert determine_visibility(TEST_INPUT)[1] == 8
# Result
with open('data/day8.txt') as _file:
input = _file.read().splitlines()
for i, result in enumerate(determine_visibility(input)):
print(f'Part {i + 1}:', result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment