Skip to content

Commit

Permalink
🍋 restore original day 8 solution
Browse files Browse the repository at this point in the history
  • Loading branch information
twentylemon committed Dec 8, 2023
1 parent 0fde24f commit cda49da
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/main/scala/org/lemon/advent/year2023/Day08.scala
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,22 @@ private object Day08:
.map(_.toLong)

cycle.fold(1L)(lcm)

def cycleGraph(directions: String, graph: Map[String, (String, String)]) = graph.keySet
.map(loc => (loc, directions.foldLeft(loc)((p, d) => move(p, d, graph))))
.toMap

def cyclesUntilEnd(cycle: Map[String, String], start: String) =
Iterator.iterate(start)(loc => cycle(loc))
.zipWithIndex
.dropWhile(!_._1.endsWith("Z"))
.next._2.toLong

def part2_alternate(input: String) =
val (directions, graph) = parse(input)
val cycle = cycleGraph(directions, graph)
val loop = graph.keySet.toSeq
.filter(_.endsWith("A"))
.map(cyclesUntilEnd(cycle, _))

loop.fold(1L)(lcm) * directions.length
18 changes: 18 additions & 0 deletions src/test/scala/org/lemon/advent/year2023/Day08Test.scala
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,21 @@ class Day08Test extends UnitTest:
test("part 2") {
part2(read(file(2023)(8))) shouldBe 13663968099527L
}

test("part 2 alternate example") {
val in = """|LR
|
|11A = (11B, XXX)
|11B = (XXX, 11Z)
|11Z = (11B, XXX)
|22A = (22B, XXX)
|22B = (22C, 22C)
|22C = (22Z, 22Z)
|22Z = (22B, 22B)
|XXX = (XXX, XXX)""".stripMargin
part2_alternate(in) shouldBe 6
}

test("part 2 alternate") {
part2_alternate(read(file(2023)(8))) shouldBe 13663968099527L
}

0 comments on commit cda49da

Please sign in to comment.