Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a72d7cd

Browse files
Switch to the more efficient disjoint paths approach
1 parent b5e1e50 commit a72d7cd

File tree

1 file changed

+22
-22
lines changed

1 file changed

+22
-22
lines changed

‎src/main/scala/AdventOfCode2022/Day16.scala

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -28,34 +28,34 @@ object Day16:
2828
cost.toMap
2929
end bfs
3030

31-
def explore(input: Seq[String], youInitial: Int, elephantInitial: Int): Int =
31+
def explore(input: Seq[String], initial: Int): Map[Set[String], Int] =
3232
val (valves, distance, todo) = parse(input)
33-
val cache = collection.mutable.Map[(Set[String], Set[String]), Int]().withDefaultValue(-1)
34-
35-
def step(todo: Set[String], you: String, elephant: String, youTime: Int, elephantTime: Int, pressure: Int): Unit =
36-
val key = (Set(you, elephant), todo)
37-
if cache(key) >= pressure then return else cache(key) = pressure
38-
39-
for next <- todo do
40-
val remaining = youTime - distance(you)(next)
41-
if remaining > 0 then
42-
val extra = remaining * valves(next).flow
43-
step(todo - next, next, elephant, remaining, elephantTime, pressure + extra)
44-
45-
for next <- todo do
46-
val remaining = elephantTime - distance(elephant)(next)
47-
if remaining > 0 then
48-
val extra = remaining * valves(next).flow
49-
step(todo - next, you, next, youTime, remaining, pressure + extra)
33+
val score = collection.mutable.Map[Set[String], Int]().withDefaultValue(0)
34+
35+
def step(todo: Set[String], done: Set[String], from: String, time: Int, pressure: Int): Unit =
36+
score(done) = score(done).max(pressure)
37+
for
38+
next <- todo
39+
remaining = time - distance(from)(next)
40+
if remaining > 0
41+
extra = remaining * valves(next).flow
42+
do step(todo - next, done + next, next, remaining, pressure + extra)
5043
end step
5144

52-
step(todo, "AA", "AA", youInitial, elephantInitial, 0)
53-
cache.values.max
45+
step(todo, Set(), "AA", initial, 0)
46+
score.toMap
5447
end explore
5548

56-
def part1(input: Seq[String]): Int = explore(input, 30, 0)
49+
def part1(input: Seq[String]): Int = explore(input, 30).values.max
5750

58-
def part2(input: Seq[String]): Int = explore(input, 26, 26)
51+
def part2(input: Seq[String]): Int =
52+
val sets = explore(input, 26)
53+
val disjoint = for
54+
(you, score1) <- sets
55+
(elephant, score2) <- sets
56+
if you.intersect(elephant).size == 0
57+
yield score1 + score2
58+
disjoint.max
5959

6060
def main(args: Array[String]): Unit =
6161
val data = io.Source.fromResource("AdventOfCode2022/Day16.txt").getLines().toSeq

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /