diff --git a/src/main/scala/eu/sim642/adventofcode2023/Day8.scala b/src/main/scala/eu/sim642/adventofcode2023/Day8.scala index d8e062ea..9bc41060 100644 --- a/src/main/scala/eu/sim642/adventofcode2023/Day8.scala +++ b/src/main/scala/eu/sim642/adventofcode2023/Day8.scala @@ -2,7 +2,6 @@ package eu.sim642.adventofcode2023 import eu.sim642.adventofcodelib.IterableImplicits.* import eu.sim642.adventofcodelib.NumberTheory -import eu.sim642.adventofcodelib.cycle.NaiveCycleFinder object Day8 { @@ -11,48 +10,21 @@ object Day8 { case class Input(instructions: Seq[Char], network: Network) - def followInstructionsSteps(input: Input): Int = { + def iterateInstructions(input: Input, startNode: Node): Iterator[Node] = { val Input(instructions, network) = input - instructions.cycle.scanLeft("AAA")({ + instructions.cycle.scanLeft(startNode)({ case (node, 'L') => network(node)._1 case (node, 'R') => network(node)._2 - }).indexOf("ZZZ") + }) } - //def followInstructionsStepsGhost(input: Input): Int = { - // val Input(instructions, network) = input - // val startNodes = network.keys.filter(_.endsWith("A")).toSeq - // instructions.cycle.scanLeft(startNodes)({ (nodes, instruction) => - // nodes.map({ node => (node, instruction) match { - // case (node, 'L') => network(node)._1 - // case (node, 'R') => network(node)._2 - // }}) - // }).indexWhere(_.forall(_.endsWith("Z"))) - //} + def followInstructionsSteps(input: Input): Int = + iterateInstructions(input, "AAA").indexOf("ZZZ") def followInstructionsStepsGhost(input: Input): Long = { - val Input(instructions, network) = input - - def helper(startNode: Node): Int = { - //var nodes = instructions.zipWithIndex.cycle.scanLeft((instructions.size - 1, startNode))({ - // case ((i, node), ('L', j)) => j -> network(node)._1 - // case ((i, node), ('R', j)) => j -> network(node)._2 - //}) - //println(NaiveCycleFinder.find(nodes).get) - val nodes = instructions.cycle.scanLeft(startNode)({ - case (node, 'L') => network(node)._1 - case (node, 'R') => network(node)._2 - }) - val x = nodes.indexWhere(_.endsWith("Z")) - println(s"$startNode -> $x") - x - //??? - } - - val startNodes = network.keys.filter(_.endsWith("A")).toSeq - println(startNodes) - val steps = startNodes.map(helper) - NumberTheory.lcm(steps.map(_.toLong)) + val startNodes = input.network.keys.filter(_.endsWith("A")) + val steps = startNodes.map(iterateInstructions(input, _).indexWhere(_.endsWith("Z"))) + NumberTheory.lcm(steps.map(_.toLong).toSeq) }