Created
December 4, 2023 13:31
-
-
Save luqmansen/335d62e2ac239f04b1eeef483aeb0296 to your computer and use it in GitHub Desktop.
advent of code 2023 day 2
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
@dataclass | |
class GameSet: | |
red: int = 0 | |
green: int = 0 | |
blue: int = 0 | |
def match_rule(self, rule: 'GameSet'): | |
if any([ | |
self.blue > rule.blue, | |
self.red > rule.red, | |
self.green > rule.green | |
]): | |
return False | |
return True | |
@dataclass | |
class Game: | |
id: int | |
sets: List[GameSet] | |
def parse_from_raw_sets(raw_sets) -> List[GameSet]: | |
""" | |
raw_sets string format: | |
"1 green, 1 red, 10 blue; 12 blue; 2 red, 9 blue" | |
""" | |
game_set = [] | |
# `sets` format = ["1 green, 1 red, 10 blue", 12 blue, 2 red, 9 blue] | |
for sets in raw_sets.split(';'): | |
# `colors` format = [1 green, 1 red, 10 blue] | |
gameset = GameSet() | |
for colors in sets.split(','): | |
num, color = colors.strip().split(' ') | |
setattr(gameset, color, int(num)) | |
game_set.append(gameset) | |
return game_set | |
def parse_line(line: str) -> 'Game': | |
""" | |
limit string format: | |
"Game 73: 1 green, 1 red, 10 blue; 12 blue; 2 red, 9 blue" | |
""" | |
raw_game, raw_sets = line.split(':') | |
_, game_id = raw_game.split(' ') | |
return Game( | |
id=int(game_id), | |
sets=parse_from_raw_sets(raw_sets), | |
) | |
if __name__ == '__main__': | |
''' | |
https://adventofcode.com/2023/day/2 | |
get full input at https://adventofcode.com/2023/day/2/input | |
''' | |
game_collection = [] | |
for line in _input.split("\n"): | |
game_collection.append(parse_line(line)) | |
# Limit 12 red cubes, 13 green cubes, and 14 blue cubes | |
rule_limit = GameSet( | |
red=12, | |
green=13, | |
blue=14, | |
) | |
matching_rule = set() | |
for game in game_collection: | |
all_match = all( | |
[ | |
sets.match_rule(rule_limit) | |
for sets in game.sets | |
] | |
) | |
if all_match: | |
matching_rule.add(game.id) | |
print(f'{game.id} match') | |
else: | |
print(f'{game.id} not match: {game.sets}') | |
print(sum(matching_rule)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment