Skip to content

Commit 5faf1dc

Browse files
committed
Add another implementation
1 parent 8695183 commit 5faf1dc

File tree

1 file changed

+24
-5
lines changed

1 file changed

+24
-5
lines changed

day21/src/day21.scala

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -191,16 +191,35 @@ def solve(robots: Int, goals: List[String], func: (Int, String) => Int): Int =
191191
shortest * goal.dropRight(1).toInt
192192
}.sum
193193

194+
// Algorithm/approach inspired by https://www.reddit.com/r/adventofcode/comments/1hj2odw/comment/m36j01x
195+
196+
val SHORTEST_PATHS = PadType.Num.shortestPaths ++ PadType.Dir.shortestPaths
197+
198+
def shortestProgramLengthClever(robots: Int, goal: String): Int =
199+
// TODO: Memoize
200+
if robots < 0 then
201+
goal.length
202+
else
203+
var current = 'A'
204+
var length = 0
205+
for next <- goal do
206+
length += moveCount(robots, current, next)
207+
current = next
208+
length
209+
210+
def moveCount(robots: Int, current: Char, next: Char): Int =
211+
if current == next then
212+
1
213+
else
214+
shortestProgramLengthClever(robots - 1, SHORTEST_PATHS((current, next)))
215+
194216
@main def main(path: String) =
195217
val goals = Source.fromFile(path).getLines.toList
196218
// println(s"Part 1: ${solve(2, goals)}")
197219
// println(s"Part 2: ${solve(25, goals)}")
198220

199-
println(PadType.Num.shortestPaths)
200-
println(PadType.Dir.shortestPaths)
201-
202-
// for i <- (0 to 3) do
203-
// println(s"${solve(i, goals, { (r, g) => shortestProgram(r, g).length })} vs ${solve(i, goals, shortestProgramLength)}")
221+
for i <- (0 to 3) do
222+
println(s"${solve(i, goals, { (r, g) => shortestProgram(r, g).length })} vs ${solve(i, goals, shortestProgramLength)} vs ${solve(i, goals, shortestProgramLengthClever)}")
204223

205224
// for c <- ('0' to '5') do
206225
// println(s"$c -> ${(0 to 3).map { i => shortestProgram(makeState(i), s"$c").length }}")

0 commit comments

Comments
 (0)