@@ -72,11 +72,11 @@ case class State(pads: List[Pad] = List(), output: String = "") {
72
72
State (newPads, newOutput)
73
73
}
74
74
75
- case class Node (state : State = State (), program : String = " " ) extends Ordered [Node ] {
76
- def compare (that : Node ): Int = that.program.length() compare program.length() // Intentionally reversed for min-heap
75
+ case class Node (state : State = State (), programLength : Int = 0 ) extends Ordered [Node ] {
76
+ def compare (that : Node ): Int = that.programLength compare programLength // Intentionally reversed for min-heap
77
77
}
78
78
79
- def shortestProgram (startState : State , goal : String ): String =
79
+ def shortestProgramLength (startState : State , goal : String ): Int =
80
80
// Your run-of-the-mill Dijkstra implementation
81
81
82
82
val queue = mutable.PriorityQueue [Node ]()
@@ -89,7 +89,7 @@ def shortestProgram(startState: State, goal: String): String =
89
89
while ! queue.isEmpty do
90
90
val node = queue.dequeue()
91
91
if node.state.output == goal then
92
- return node.program
92
+ return node.programLength
93
93
94
94
if node.state.output.length < goal.length then
95
95
for
@@ -98,15 +98,15 @@ def shortestProgram(startState: State, goal: String): String =
98
98
do
99
99
if ! visited.contains(newState) then
100
100
visited.add(newState)
101
- queue.enqueue(Node (newState, node.program.appended(action) ))
101
+ queue.enqueue(Node (newState, node.programLength + 1 ))
102
102
103
103
throw new RuntimeException (" No shortest program found" )
104
104
105
105
def solve (robots : Int , goals : List [String ]): Int =
106
106
val pads = List .fill(robots)(Pad (PadType .Dir )) :+ Pad (PadType .Num )
107
107
goals.map { goal =>
108
- val shortest = shortestProgram (State (pads), goal)
109
- shortest.length * goal.dropRight(1 ).toInt
108
+ val shortest = shortestProgramLength (State (pads), goal)
109
+ shortest * goal.dropRight(1 ).toInt
110
110
}.sum
111
111
112
112
@ main def main (path : String ) =
0 commit comments