Created
December 10, 2023 18:19
-
-
Save luqmansen/b8553331d8049e1a87897c29ad6e589b to your computer and use it in GitHub Desktop.
Advent of Code Day 5 part 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from dataclasses import dataclass | |
from typing import List | |
@dataclass | |
class Mapping: | |
destination_range_start: int | |
source_range_start: int | |
range_length: int | |
def is_input_in_range(self, input_num) -> bool: | |
return self.source_range_start <= \ | |
input_num <= \ | |
self.source_range_start + self.range_length | |
def translate(self, input_num: int) -> int: | |
offset = int(input_num) - self.source_range_start | |
return self.destination_range_start + offset | |
@dataclass | |
class MapCollections: | |
name: str | |
maps: List[Mapping] | |
def _find_used_map(self, input_num): | |
for m in self.maps: | |
if m.is_input_in_range(input_num): | |
return m | |
return None | |
def translate(self, input_num): | |
m = self._find_used_map(input_num) | |
return m.translate(input_num) if m else input_num | |
def parse_raw_mapping(input_str) -> List[MapCollections]: | |
mapping_collections = [] | |
raw_lines = input_str.split('\n')[2:] | |
for ix, line in enumerate(raw_lines): | |
raw_line_parsed = line.strip().split('map:') | |
if len(raw_line_parsed) == 2: | |
collection = MapCollections( | |
name=raw_line_parsed[0].strip(), | |
maps=[] | |
) | |
for line_data in raw_lines[ix+1:]: | |
curr = line_data.strip().split(' ') | |
if len(curr) != 3: | |
# source, dst, range has exactly 3 items | |
break | |
collection.maps.append( | |
Mapping( | |
destination_range_start=int(curr[0]), | |
source_range_start=int(curr[1]), | |
range_length=int(curr[2]) | |
) | |
) | |
mapping_collections.append(collection) | |
return mapping_collections | |
def parse_raw_seeds(input_str) -> List[int]: | |
raw_seeds = input_str.split('\n')[0].split(':')[1].strip() | |
return raw_seeds.split(' ') | |
def solve(input_str): | |
seeds = parse_raw_seeds(input_str) | |
mapping_collection = parse_raw_mapping(input_str) | |
locations = [] | |
for seed in seeds: | |
curr_input = int(seed) | |
for mapping in mapping_collection: | |
curr_input = mapping.translate(curr_input) | |
locations.append(curr_input) | |
return min(locations) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment