Skip to content

Commit 204ae79

Browse files
committed
Optimize 2020 day 22 part 2 using "supercard" optimization
No difference on my input, 20× difference on mstksg input.
1 parent b2eae75 commit 204ae79

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

src/main/scala/eu/sim642/adventofcode2020/Day22.scala

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,19 @@ object Day22 {
6969
case (card1 +: newDeck1, card2 +: newDeck2) =>
7070
val winner: Either[Any, Any] = {
7171
if (newDeck1.lengthIs >= card1 && newDeck2.lengthIs >= card2) {
72-
val recDecks = (newDeck1.take(card1), newDeck2.take(card2))
73-
playWinner(recDecks)
72+
val recDec1 = newDeck1.take(card1)
73+
val recDec2 = newDeck2.take(card2)
74+
// "Supercard" optimization:
75+
// https://github.com/glguy/advent2020/blob/1776cb3388581a1fbab79f1802650d43e24ffa66/execs/Day22.hs#L62-L65
76+
// No difference on my input, 20× difference on mstksg input
77+
val recDec1Max = recDec1.max
78+
val recDec2Max = recDec2.max
79+
if (recDec1Max > recDec2Max && recDec1Max >= (card1 + card2))
80+
Left(())
81+
else {
82+
val recDecks = (recDec1, recDec2)
83+
playWinner(recDecks)
84+
}
7485
} else {
7586
if (card1 > card2)
7687
Left(())

src/test/scala/eu/sim642/adventofcode2020/Day22Test.scala

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ class Day22Test extends AnyFunSuite {
2020
|7
2121
|10""".stripMargin
2222

23+
lazy val mstksgInput: String = io.Source.fromInputStream(getClass.getResourceAsStream("day22mstksg.txt")).mkString.trim
24+
2325
test("Part 1 examples") {
2426
assert(Part1.winningScore(parseDecks(exampleInput)) == 306)
2527
}
@@ -35,4 +37,8 @@ class Day22Test extends AnyFunSuite {
3537
test("Part 2 input answer") {
3638
assert(Part2.winningScore(parseDecks(input)) == 32317)
3739
}
40+
41+
test("Part 2 mstksg") {
42+
assert(Part2.winningScore(parseDecks(mstksgInput)) == 32760) // unconfirmed answer
43+
}
3844
}

0 commit comments

Comments
 (0)