zerosleeps

Since 2010

Advent of Code 2022 day 8

Not very pleased with the code I’m about to post for Advent of Code 2022 day 8. It has loads of replication and dumb use of variables. No unit tests either. But… it works and that’s got to be better than beautiful code that doesn’t work.

import math
from utils import get_raw_input


def parse_raw_input(raw_input):
    return [[int(c) for c in line] for line in raw_input]


def shorter_than_current_node(other_node, current_node):
    return other_node < current_node


def viewing_distance(other_nodes, current_node):
    can_see = 0
    for node in other_nodes:
        if node < current_node:
            can_see += 1
        else:
            can_see += 1
            break
    return can_see


def part_one(input):
    can_be_seen = 0
    for y in range(len(input)):
        for x in range(len(input[y])):
            north = [row[x] for row in input][:y]
            east = input[y][x + 1 :]
            south = [row[x] for row in input][y + 1 :]
            west = input[y][:x]
            if (
                all([shorter_than_current_node(node, input[y][x]) for node in north])
                or all([shorter_than_current_node(node, input[y][x]) for node in east])
                or all([shorter_than_current_node(node, input[y][x]) for node in south])
                or all([shorter_than_current_node(node, input[y][x]) for node in west])
            ):
                can_be_seen += 1
    return can_be_seen


def part_two(input):
    best_score = 0
    for y in range(len(input)):
        for x in range(len(input[y])):
            north = list(reversed([row[x] for row in input][:y]))
            east = input[y][x + 1 :]
            south = [row[x] for row in input][y + 1 :]
            west = list(reversed(input[y][:x]))
            current_node_distances = [
                viewing_distance(north, input[y][x]),
                viewing_distance(east, input[y][x]),
                viewing_distance(south, input[y][x]),
                viewing_distance(west, input[y][x]),
            ]
            scenic_score = math.prod(current_node_distances)
            if scenic_score > best_score:
                best_score = scenic_score
    return best_score


if __name__ == "__main__":
    parsed_input = parse_raw_input(get_raw_input("day_08_input.txt"))
    print(part_one(parsed_input))
    print(part_two(parsed_input))