From 446affa69f1838bd60ebec3e4da9667e282ef7ea Mon Sep 17 00:00:00 2001 From: Thibaud Date: Fri, 8 Dec 2023 14:24:07 +0100 Subject: [PATCH] day 8 part 2 --- day8/day8.py | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/day8/day8.py b/day8/day8.py index f2cde82..8c19236 100644 --- a/day8/day8.py +++ b/day8/day8.py @@ -1,4 +1,5 @@ import re +import math from itertools import cycle def parse_input(infile): @@ -23,42 +24,42 @@ def part1(directions, nodes): current_node = nodes[current_node][0] else: current_node = nodes[current_node][1] - print(f"Reached 'ZZZ' in {iterations} iterations") + print(f"Part 1: reached 'ZZZ' in {iterations} iterations") def part2(directions, nodes): current_nodes = [k for k in nodes.keys() if k.endswith("A")] + # keep track of iterations number for each visited node + # (the number will stop to beeing incremented once the node n_i value reached the target value 'xxZ') iterations = [0] * len(current_nodes) - print(current_nodes, iterations) for d in cycle(directions): if all(c.endswith("Z") for c in current_nodes): break - #iterations += len(current_nodes) + if d == "L": new_nodes = [] for i, n in enumerate(current_nodes): - if not n.endswith("Z"): + if n.endswith("Z"): # end condition already reached for this node + new_nodes.append(n) + else: new_nodes.append(nodes[n][0]) iterations[i] += 1 - else: - new_nodes.append(n) current_nodes = new_nodes - #current_nodes = [c if c.endswith("Z") else nodes[c][0] for c in current_nodes] else: new_nodes = [] for i, n in enumerate(current_nodes): - if not n.endswith("Z"): + if n.endswith("Z"): # end condition already reached for this node + new_nodes.append(n) + else: new_nodes.append(nodes[n][1]) iterations[i] += 1 - else: - new_nodes.append(n) current_nodes = new_nodes - #current_nodes = [c if c.endswith("Z") else nodes[c][1] for c in current_nodes] - print(current_nodes, iterations) - - - print(f"Reached all nodes such that 'xxZ' in {iterations} iterations") + + # the result is the lowest common multiple between the number of iterations + # for each node + result = math.lcm(*iterations) + print(f"Part 2: reached all nodes such that 'xxZ' in {result} iterations") if __name__ == "__main__":