-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAdvent10.scala
246 lines (204 loc) · 6.81 KB
/
Advent10.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
package jurisk.adventofcode.y2023
import cats.implicits._
import jurisk.adventofcode.y2023.pipe.Pipe
import jurisk.adventofcode.y2023.pipe.Pipe._
import jurisk.algorithms.pathfinding.Bfs
import jurisk.algorithms.pathfinding.Dijkstra
import jurisk.geometry.Coords2D
import jurisk.geometry.CoordsAndDirection2D
import jurisk.geometry.Direction2D.E
import jurisk.geometry.Direction2D.N
import jurisk.geometry.Direction2D.S
import jurisk.geometry.Direction2D.W
import jurisk.geometry.Field2D
import jurisk.utils.CollectionOps.IterableOps
import jurisk.utils.FileInput._
import jurisk.utils.Parsing.StringOps
import scala.collection.immutable.ArraySeq
object Advent10 {
final case class Input(
animalAt: Coords2D,
field: Field2D[Pipe],
) {
def at(coords: Coords2D): Pipe =
field.atOrElse(coords, Empty)
}
object Input {
def parse(s: String): Input = {
val chars: Field2D[Char] = Field2D.parseCharField(s)
val animalAt = chars.filterCoordsByValue('S').singleResultUnsafe
val mapping = Map(
'|' -> N_S,
'-' -> E_W,
'L' -> N_E,
'J' -> N_W,
'7' -> S_W,
'F' -> S_E,
'.' -> Empty,
'S' -> Empty,
)
val field: Field2D[Pipe] = Field2D.parse(s, mapping.apply)
// Find a suitable pipe to replace the `S` animal cell
val animalPipe = Pipe.NonEmpty.filter { candidate =>
candidate.connections.forall { direction =>
field
.atOrElse(animalAt + direction, Empty)
.connections
.contains(direction.invert)
}
}.singleElementUnsafe
val updatedField = field.updatedAtUnsafe(animalAt, animalPipe)
Input(animalAt, updatedField)
}
}
def parse(input: String): Input = Input.parse(input)
private def dijkstraToAllTrackNodes(data: Input) = Dijkstra
.dijkstraAll(
data.animalAt,
(c: Coords2D) => connectedNeighbours(data.field, c).map(x => (x, 1)),
)
// Find distance to all nodes we can get to while going on the track, take the maximum
def part1(data: Input): Int =
dijkstraToAllTrackNodes(data).map {
case (coord @ _, (parent @ _, distance)) =>
distance
}.max
def part2(data: Input): Long = {
val fromPicksShoelace = part2PicksShoelace(data)
val fromMarkRightSideOfTrack = part2MarkRightSideOfTrack(data)
val from3x3Expansion = part2From3x3Expansion(data)
assert(
Set(
fromPicksShoelace,
fromMarkRightSideOfTrack,
from3x3Expansion,
).size == 1,
s"Expected to get same results: $fromPicksShoelace and $fromMarkRightSideOfTrack and $from3x3Expansion",
)
fromPicksShoelace
}
private def findStart(onlyTrack: Field2D[Pipe]): CoordsAndDirection2D = {
// We don't know which direction is inside and which is outside for the animal coordinates,
// but we can figure it out for the top left coordinates. This depends on the order in which `allCoords`
// returns coordinates.
val topLeftFullCoord = onlyTrack.allCoords
.find(x => onlyTrack.atOrElse(x, Empty) != Empty)
.getOrElse("Failed to find".fail)
val topLeftFullValue = onlyTrack.atOrElse(topLeftFullCoord, Empty)
val topLeftStartDirection = topLeftFullValue match {
case Pipe.Empty => "Unexpected".fail
case Pipe.N_S => S
case Pipe.E_W => W
case Pipe.N_E => N
case Pipe.N_W => W
case Pipe.S_W => S
case Pipe.S_E => E
}
CoordsAndDirection2D(
coords = topLeftFullCoord,
direction = topLeftStartDirection,
)
}
private def walkTrack(data: Field2D[Pipe]) = {
val start = findStart(data)
Bfs
.bfsReachable[CoordsAndDirection2D](
start,
x => nextOnTrack(x, data) :: Nil,
)
}
private def extractTrack(data: Input): (Set[Coords2D], Field2D[Pipe]) = {
// All the track coordinates
val trackCoords = dijkstraToAllTrackNodes(data).keySet
// The field with only track cells left, others are Empty
val onlyTrack = data.field.mapByCoordsWithValues { case (c, v) =>
if (trackCoords.contains(c)) v else Empty
}
(trackCoords, onlyTrack)
}
def part2PicksShoelace(data: Input): Long = {
val (trackCoords @ _, onlyTrack) = extractTrack(data)
// Which direction was the animal facing on each track segment?
val trackCoordsWithAnimalDirection = walkTrack(onlyTrack)
// Track coordinates in walking order
val trackCoordsInWalkingOrder = ArraySeq.from(
trackCoordsWithAnimalDirection
.map(_.coords)
)
Coords2D.interiorPointsExcludingBoundary(trackCoordsInWalkingOrder)
}
def part2MarkRightSideOfTrack(data: Input): Long = {
val (trackCoords, onlyTrack) = extractTrack(data)
// Which direction was the animal facing on each track segment?
val trackCoordsWithAnimalDirection = walkTrack(onlyTrack)
// Which cells were on the right of the track, as the animal was walking around it?
val rightCoordinateSeeds = trackCoordsWithAnimalDirection
.flatMap(x => coordsToTheRight(x, data.field).toSet)
.toSet
.diff(trackCoords)
// Let's flood-fill from the coordinates which we know are on the right side of the track
val floodFilled = rightCoordinateSeeds.flatMap { c =>
Bfs.bfsReachable[Coords2D](
c,
x => data.field.adjacent4(x).toSet.diff(trackCoords).toList,
)
}
floodFilled.size
}
def part2From3x3Expansion(data: Input): Long = {
val (_, onlyTrack) = extractTrack(data)
val mapping: Pipe => String = {
case Pipe.Empty =>
"""...
|...
|...
|""".stripMargin
case Pipe.N_S =>
""".#.
|.#.
|.#.
|""".stripMargin
case Pipe.E_W =>
"""...
|###
|...
|""".stripMargin
case Pipe.N_E =>
""".#.
|.##
|...
|""".stripMargin
case Pipe.N_W =>
""".#.
|##.
|...
|""".stripMargin
case Pipe.S_W =>
"""...
|##.
|.#.
|""".stripMargin
case Pipe.S_E =>
"""...
|.##
|.#.
|""".stripMargin
}
val expanded = onlyTrack.flatMap { pipe =>
Field2D.parseBooleanField(mapping(pipe))
}
Field2D.printBooleanField(expanded)
val floodFilled = Field2D
.floodFillField[Boolean](expanded, Coords2D.Zero, (_, to) => !to, true)
Field2D.printBooleanField(floodFilled)
val chunked = floodFilled.chunkIntoSubfields(3, 3)
chunked.count(x => x.forall(_ == false))
}
def parseFile(fileName: String): Input =
parse(readFileText(fileName))
def main(args: Array[String]): Unit = {
val realData: Input = parseFile("2023/10.txt")
println(s"Part 1: ${part1(realData)}")
println(s"Part 2: ${part2(realData)}")
}
}