Skip to content

Commit 71ed0ad

Browse files
committed
remove withFilter adn try/finally
1 parent cea56d0 commit 71ed0ad

File tree

1 file changed

+20
-17
lines changed

1 file changed

+20
-17
lines changed

2022/src/day16.scala

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -103,30 +103,33 @@ def bestPath(map: RoomsInfo, start: Id, valves: Set[Id], timeAllowed: Int): Int
103103
val _activeValveIndices = Array.fill[Boolean](valveCount + 1)(true) // add an extra valve for the initial state
104104
def valveIndexLeft(i: Int) = _activeValveIndices(i)
105105
def withoutValve(i: Int)(f: => Int) =
106-
try
107-
_activeValveIndices(i) = false
108-
f
109-
finally _activeValveIndices(i) = true
106+
_activeValveIndices(i) = false
107+
val result = f
108+
_activeValveIndices(i) = true
109+
result
110110
val roomsByIndices = IArray.tabulate(valveCount)(i => map.rooms(valvesLookup(i)))
111111

112112
def recurse(hiddenValve: Int, current: Id, timeLeft: Int, totalValue: Int): Int = withoutValve(hiddenValve):
113113
// recursively consider all plausible options
114114
// we are finished when we no longer have time to reach another valve or all valves are open
115115
val routesOfCurrent = map.routes(current)
116116
var bestValue = totalValue
117-
for index <- valvesLookup.indices if valveIndexLeft(index) do
118-
val id = valvesLookup(index)
119-
val distance = routesOfCurrent(id)
120-
// how much time is left after we traverse there and open the valve?
121-
val t = timeLeft - distance - 1
122-
// if `t` is zero or less this option can be skipped
123-
if t > 0 then
124-
// the value of choosing a particular valve (over the life of our simulation)
125-
// is its flow rate multiplied by the time remaining after opening it
126-
val value = roomsByIndices(index).flow * t
127-
val recValue = recurse(hiddenValve = index, id, t, totalValue + value)
128-
if recValue > bestValue then
129-
bestValue = recValue
117+
for index <- valvesLookup.indices do
118+
if valveIndexLeft(index) then
119+
val id = valvesLookup(index)
120+
val distance = routesOfCurrent(id)
121+
// how much time is left after we traverse there and open the valve?
122+
val t = timeLeft - distance - 1
123+
// if `t` is zero or less this option can be skipped
124+
if t > 0 then
125+
// the value of choosing a particular valve (over the life of our simulation)
126+
// is its flow rate multiplied by the time remaining after opening it
127+
val value = roomsByIndices(index).flow * t
128+
val recValue = recurse(hiddenValve = index, id, t, totalValue + value)
129+
if recValue > bestValue then
130+
bestValue = recValue
131+
end if
132+
end if
130133
end for
131134
bestValue
132135
end recurse

0 commit comments

Comments
 (0)