From 71d885376d281f8ac39ef4bf4f63f054921e68c4 Mon Sep 17 00:00:00 2001 From: Sijmen Date: Mon, 25 Dec 2023 12:20:34 +0100 Subject: [PATCH] Add days 7 and 8 --- day07.py | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ day08.py | 34 ++++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 day07.py create mode 100644 day08.py diff --git a/day07.py b/day07.py new file mode 100644 index 0000000..4b7ea92 --- /dev/null +++ b/day07.py @@ -0,0 +1,59 @@ +import fileinput +from collections import Counter + +STRENGTHS = { + "A": 1, + "K": 2, + "Q": 3, + "T": 5, + "9": 6, + "8": 7, + "7": 8, + "6": 9, + "5": 10, + "4": 11, + "3": 12, + "2": 13, +} + +INPUT = [] +for line in fileinput.input(): + (hand, bid) = line.split() + counter = Counter(hand) + INPUT.append((hand, int(bid), counter["J"], counter.most_common() + [("", 0)])) + +def solve(part): + STRENGTHS["J"] = 14 if part == 2 else 4 + + hands = [] + for (hand, bid, jokers, mcs) in INPUT: + if part == 2: + mcs = [(c, i) for (c, i) in mcs if c != "J"] + else: + jokers = 0 + mc = mcs[0][1] + jokers + + if mc == 5: + strength = 1 + elif mc == 4: + strength = 2 + elif mc == 3 and mcs[1][1] == 2: + strength = 3 + elif mc == 3: + strength = 4 + elif mc == 2 and mcs[1][1] == 2: + strength = 5 + elif mc == 2: + strength = 6 + else: + strength = 7 + + strengths = [STRENGTHS[c] for c in hand] + hands.append(([strength] + strengths, bid)) + + hands.sort(key=lambda h: h[0], reverse=True) + return sum((i + 1) * bid for (i, (_, bid)) in enumerate(hands)) + +part1 = solve(part=1) +part2 = solve(part=2) +print(part1, part2) diff --git a/day08.py b/day08.py new file mode 100644 index 0000000..38cec15 --- /dev/null +++ b/day08.py @@ -0,0 +1,34 @@ +import fileinput +import math + +input = fileinput.input() + +instructions = next(input).strip() +next(input) + +tree = {} + +for line in input: + if line.strip(): + (parent, children) = line.split(" = ") + (left, right) = children[1:-2].split(", ") + tree[parent] = (left, right) + +nodes = [node for node in tree if node[2] == "A"] +cycles = [0] * len(nodes) + +for i in range(len(nodes)): + while nodes[i][2] != "Z": + for instr in instructions: + cycles[i] += 1 + if instr == "L": + (nodes[i], _) = tree[nodes[i]] + else: + (_, nodes[i]) = tree[nodes[i]] + if nodes[i][2] == "Z": + break + +part1 = cycles[nodes.index("ZZZ")] +part2 = math.lcm(*cycles) + +print(part1, part2)