8000 Solve 2020 day 24 part 2 · sim642/adventofcode@4284bcd · GitHub
[go: up one dir, main page]

Skip to content

Commit 4284bcd

Browse files
committed
Solve 2020 day 24 part 2
1 parent cd8e91d commit 4284bcd

File tree

2 files changed

+36
-3
lines changed

2 files changed

+36
-3
lines changed

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

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package eu.sim642.adventofcode2020
22

33
import eu.sim642.adventofcodelib.pos.HexPos
4+
import eu.sim642.adventofcodelib.IteratorImplicits._
45

56
object Day24 {
67

@@ -15,16 +16,39 @@ object Day24 {
1516

1617
def applyMoves(pos: HexPos, moves: Seq[String]): HexPos = moves.foldLeft(pos)(_ + neighbors(_))
1718

18-
def countBlackTiles(directions: Seq[Seq[String]]): Int = {
19+
def getBlackTiles(directions: Seq[Seq[String]]): Set[HexPos] = {
1920
directions
2021
.view
2122
.map(applyMoves(HexPos.zero, _))
2223
.groupMapReduce(identity)(_ => 1)(_ + _)
2324
.filter(_._2 % 2 == 1)
24-
.keys
25-
.size
25+
.keySet
2626
}
2727

28+
def countBlackTiles(directions: Seq[Seq[String]]): Int = getBlackTiles(directions).size
29+
30+
def step(blackTiles: Set[HexPos]): Set[HexPos] = {
31+
// based on 2020 Day 17
32+
blackTiles.iterator
33+
.flatMap(pos =>
34+
neighbors.values.iterator
35+
.map(pos + _)
36+
)
37+
.groupMapReduce(identity)(_ => 1)(_ + _)
38+
.collect({
39+
case (pos, 2) => pos
40+
case (pos, 1) if blackTiles(pos) => pos
41+
})
42+
.toSet
43+
}
44+
45+
def countBlackTilesAfter(directions: Seq[Seq[String]], days: Int = 100): Int = {
46+
val initialBlackTiles = getBlackTiles(directions)
47+
val finalBlackTiles = Iterator.iterate(initialBlackTiles)(step)(days)
48+
finalBlackTiles.size
49+
}
50+
51+
2852
private val moveRegex = """e|se|sw|w|nw|ne""".r
2953

3054
def parseMoves(s: String): Seq[String] = moveRegex.findAllIn(s).toSeq
@@ -35,5 +59,6 @@ object Day24 {
3559

3660
def main(args: Array[String]): Unit = {
3761
println(countBlackTiles(parseDirections(input)))
62+
println(countBlackTilesAfter(parseDirections(input)))
3863
}
3964
}

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,4 +34,12 @@ class Day24Test extends AnyFunSuite {
3434
test("Part 1 input answer") {
3535
assert(countBlackTiles(parseDirections(input)) == 277)
3636
}
37+
38+
test("Part 2 examples") {
39+
assert(countBlackTilesAfter(parseDirections(exampleInput)) == 2208)
40+
}
41+
42+
test("Part 2 input answer") {
43+
assert(countBlackTilesAfter(parseDirections(input)) == 3531)
44+
}
3745
}

0 commit comments

Comments
 (0)
0