From 43c89839d73a4da4a14e0853f161f7f5362e5638 Mon Sep 17 00:00:00 2001 From: Tom van der Lee Date: Thu, 8 Dec 2022 23:11:51 +0100 Subject: Improvements --- day8/__init__.py | 55 +++++++++++++++++++++++++++++-------------------------- 1 file changed, 29 insertions(+), 26 deletions(-) diff --git a/day8/__init__.py b/day8/__init__.py index 08f9925..0620e7c 100644 --- a/day8/__init__.py +++ b/day8/__init__.py @@ -1,6 +1,5 @@ # -*- coding: utf-8 -*- -from abc import ABC -from typing import Iterator, Any, List +from typing import Iterator, Any, List, Tuple from aoc import BaseAssignment @@ -14,6 +13,14 @@ class Assignment(BaseAssignment): def col_at(self, x: int) -> List[int]: return [int(i[x]) for i in self.trees] + def inner_trees(self) -> Iterator[Tuple[int, int]]: + width = len(self.trees[0]) + height = len(self.trees) + + for x in range(1, width - 1): + for y in range(1, height - 1): + yield x, y + class AssignmentOne(Assignment): example_result = 21 @@ -42,10 +49,9 @@ class AssignmentOne(Assignment): self.is_visible(self.col_at(1), 2) - for x in range(1, width - 1): - for y in range(1, height - 1): - if self.tree_visible(x, y): - visible_inside += 1 + for x, y in self.inner_trees(): + if self.tree_visible(x, y): + visible_inside += 1 return visible_inside + ((width - 1) * 2) + ((height - 1) * 2) @@ -53,24 +59,25 @@ class AssignmentOne(Assignment): class AssignmentTwo(Assignment): example_result = 8 - @staticmethod - def calculate_1d_scenic_score(trees: List[int], index: int) -> int: + @classmethod + def calculate_score(cls, value: int, values: List[int]) -> int: + score = 0 + for score, v in enumerate(values): + if v >= value: + break + + return score + 1 + + @classmethod + def calculate_1d_scenic_score(cls, trees: List[int], index: int) -> int: first_half = list(reversed(trees[:index])) second_half = trees[index + 1 :] value = trees[index] - score_first_half = 0 - for score_first_half, tree in enumerate(first_half): - if tree >= value: - break - - score_second_half = 0 - for score_second_half, tree in enumerate(second_half): - if tree >= value: - break - - return (score_first_half + 1) * (score_second_half + 1) + return cls.calculate_score(value, first_half) * cls.calculate_score( + value, second_half + ) def calculate_scenic_score(self, x: int, y: int) -> int: col = self.col_at(x) @@ -83,14 +90,10 @@ class AssignmentTwo(Assignment): def run(self, input: Iterator) -> Any: self.trees = list(input) - width = len(self.trees[0]) - height = len(self.trees) - scenic_scores: List[int] = [] - for x in range(1, width - 1): - for y in range(1, height - 1): - scenic_score = self.calculate_scenic_score(x, y) - scenic_scores.append(scenic_score) + for x, y in self.inner_trees(): + scenic_score = self.calculate_scenic_score(x, y) + scenic_scores.append(scenic_score) return max(scenic_scores) -- cgit v1.2.3