-
Notifications
You must be signed in to change notification settings - Fork 0
/
day 8.dib
407 lines (303 loc) · 12.1 KB
/
day 8.dib
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
#!meta
{"kernelInfo":{"defaultKernelName":"csharp","items":[{"aliases":[],"name":"csharp"},{"aliases":[],"languageName":"fsharp","name":"fsharp"}]}}
#!markdown
# --- Day 8: Haunted Wasteland ---
You're still riding a camel across Desert Island when you spot a sandstorm quickly approaching. When you turn to warn the Elf, she disappears before your eyes! To be fair, she had just finished warning you about ghosts a few minutes ago.
One of the camel's pouches is labeled "maps" - sure enough, it's full of documents (your puzzle input) about how to navigate the desert. At least, you're pretty sure that's what they are; one of the documents contains a list of left/right instructions, and the rest of the documents seem to describe some kind of network of labeled nodes.
It seems like you're meant to use the left/right instructions to navigate the network. Perhaps if you have the camel follow the same instructions, you can escape the haunted wasteland!
After examining the maps for a bit, two nodes stick out: AAA and ZZZ. You feel like AAA is where you are now, and you have to follow the left/right instructions until you reach ZZZ.
This format defines each node of the network individually. For example:
```
RL
AAA = (BBB, CCC)
BBB = (DDD, EEE)
CCC = (ZZZ, GGG)
DDD = (DDD, DDD)
EEE = (EEE, EEE)
GGG = (GGG, GGG)
ZZZ = (ZZZ, ZZZ)
```
Starting with AAA, you need to look up the next element based on the next left/right instruction in your input. In this example, start with AAA and go right (R) by choosing the right element of AAA, CCC. Then, L means to choose the left element of CCC, ZZZ. By following the left/right instructions, you reach ZZZ in 2 steps.
Of course, you might not find ZZZ right away. If you run out of left/right instructions, repeat the whole sequence of instructions as necessary: RL really means RLRLRLRLRLRLRLRL... and so on. For example, here is a situation that takes 6 steps to reach ZZZ:
```
LLR
AAA = (BBB, BBB)
BBB = (AAA, ZZZ)
ZZZ = (ZZZ, ZZZ)
```
Starting at AAA, follow the left/right instructions. How many steps are required to reach ZZZ?
#!fsharp
type Node = {
id: string
left: string
right: string
}
type Direction = Left | Right
let parseLine (input: string) = {
id = input[0..2]
left = input[7..9]
right = input[12..14]
}
type ChallengeInput = {
directions: Direction array
nodes: Map<string, Node>
}
let parseDirection = function
| 'L' -> Left
| 'R' -> Right
| c -> raise (InvalidOperationException $"Could not parse direction ${c}")
let parseInput (input: string array) =
{
directions =
input[0]
|> Seq.map parseDirection
|> Array.ofSeq
nodes =
input[2..]
|> Seq.map (parseLine >> fun node -> (node.id, node))
|> Map.ofSeq
}
let sampleInput1 =
[|
"RL"
""
"AAA = (BBB, CCC)"
"BBB = (DDD, EEE)"
"CCC = (ZZZ, GGG)"
"DDD = (DDD, DDD)"
"EEE = (EEE, EEE)"
"GGG = (GGG, GGG)"
"ZZZ = (ZZZ, ZZZ)"
|]
|> parseInput
sampleInput1
#!fsharp
let sampleInput2 =
[|
"LLR"
""
"AAA = (BBB, BBB)"
"BBB = (AAA, ZZZ)"
"ZZZ = (ZZZ, ZZZ)"
|]
|> parseInput
sampleInput2
#!fsharp
let followDirection (nodes: Map<string, Node>) (current: string) (direction: Direction) =
match direction with
| Left -> nodes[current].left
| Right -> nodes[current].right
let rec next (input: ChallengeInput) (index: int) (node: string) =
seq {
yield node
let nextIndex = (index + 1) % input.directions.Length
let nextNode = followDirection input.nodes node input.directions[index]
yield! next input nextIndex nextNode
}
let followDirections (input: ChallengeInput) =
next input 0 "AAA"
|> Seq.takeWhile (fun node -> node <> "ZZZ")
followDirections sampleInput1
#!fsharp
let challengeInput =
File.ReadAllLinesAsync "day 8 input.txt"
|> Async.AwaitTask
|> Async.RunSynchronously
|> parseInput
followDirections challengeInput |> Seq.length
#!markdown
## --- Part Two ---
The sandstorm is upon you and you aren't any closer to escaping the wasteland. You had the camel follow the instructions, but you've barely left your starting position. It's going to take significantly more steps to escape!
What if the map isn't for people - what if the map is for ghosts? Are ghosts even bound by the laws of spacetime? Only one way to find out.
After examining the maps a bit longer, your attention is drawn to a curious fact: the number of nodes with names ending in A is equal to the number ending in Z! If you were a ghost, you'd probably just start at every node that ends with A and follow all of the paths at the same time until they all simultaneously end up at nodes that end with Z.
For example:
```
LR
11A = (11B, XXX)
11B = (XXX, 11Z)
11Z = (11B, XXX)
22A = (22B, XXX)
22B = (22C, 22C)
22C = (22Z, 22Z)
22Z = (22B, 22B)
XXX = (XXX, XXX)
```
Here, there are two starting nodes, 11A and 22A (because they both end with A). As you follow each left/right instruction, use that instruction to simultaneously navigate away from both nodes you're currently on. Repeat this process until all of the nodes you're currently on end with Z. (If only some of the nodes you're on end with Z, they act like any other node and you continue as normal.) In this example, you would proceed as follows:
* Step 0: You are at 11A and 22A.
* Step 1: You choose all of the left paths, leading you to 11B and 22B.
* Step 2: You choose all of the right paths, leading you to 11Z and 22C.
* Step 3: You choose all of the left paths, leading you to 11B and 22Z.
* Step 4: You choose all of the right paths, leading you to 11Z and 22B.
* Step 5: You choose all of the left paths, leading you to 11B and 22C.
* Step 6: You choose all of the right paths, leading you to 11Z and 22Z.
So, in this example, you end up entirely on nodes that end in Z after 6 steps.
Simultaneously start on every node that ends with A. How many steps does it take before you're only on nodes that end with Z?
#!fsharp
#!import shared.fs
open Shared
let sampleInput3 =
[|
"LR"
""
"11A = (11B, XXX)"
"11B = (XXX, 11Z)"
"11Z = (11B, XXX)"
"22A = (22B, XXX)"
"22B = (22C, 22C)"
"22C = (22Z, 22Z)"
"22Z = (22B, 22B)"
"XXX = (XXX, XXX)"
|]
|> parseInput
let isStartingNode (node: string) = node[2] = 'A'
let isEndingNode (node: string) = node[2] = 'Z'
let startingNodes (input: ChallengeInput) =
input.nodes.Keys
|> Seq.filter isStartingNode
|> Array.ofSeq
let ghostWalks (input: ChallengeInput) =
startingNodes input
|> Array.map (next input 0)
|> transposeSequences
|> Seq.takeWhile (Array.exists (not << isEndingNode))
ghostWalks sampleInput3
#!fsharp
ghostWalks challengeInput
|> Seq.indexed
|> Seq.where (fun (i, nodes) -> nodes |> Seq.filter isEndingNode |> Seq.length > 1)
|> Seq.take 10
#!markdown
The previous approach seems too slow / inefficient. Let's try with a single sequence generator, rather than re-using the same individual sequence generator 6 times
#!fsharp
let rec next' (input: ChallengeInput) (index: int) (nodes: string array) =
seq {
yield nodes
let nextIndex = (index + 1) % input.directions.Length
let nextNodes =
nodes
|> Array.map (fun n -> followDirection input.nodes n input.directions[index])
yield! next' input nextIndex nextNodes
}
let ghostWalks' (input: ChallengeInput) =
startingNodes input
|> next' input 0
|> Seq.takeWhile (Array.exists (not << isEndingNode))
ghostWalks' challengeInput |> Seq.take 100
#!markdown
I think I should figure out the sequence length for each starting position and see if we can use that to determine how long before each option lands on an exit node.
But first, I want to try optimising the code as much as possible
#!fsharp
open System.Collections.Generic
type Node' = {
id: string
isStartNode : bool
isEndNode : bool
[<DefaultValue>] mutable left: Node'
[<DefaultValue>] mutable right: Node'
}
let buildNodeGraph (input: ChallengeInput) =
let nodes = Dictionary<string, Node'> ()
let rec buildNode' (node: Node) =
match nodes.TryGetValue(node.id) with
| (true, result) -> result
| (false, _) ->
let mutable result = {
id = node.id
isStartNode = isStartingNode node.id
isEndNode = isEndingNode node.id
}
nodes.Add(node.id, result)
result.left <- buildNode' input.nodes[node.left]
result.right <- buildNode' input.nodes[node.right]
result
input.nodes.Values |> Seq.map buildNode' |> Array.ofSeq
let rec countToEndNode (input: ChallengeInput) (current: Node' array) (index: int) (count: int64) =
if current |> Array.forall (fun node -> node.isEndNode)
then count
else
let direction = input.directions[index]
// Assign back into the input array to prevent allocations
for i in 0..current.Length - 1 do
match direction with
| Left -> current[i] <- current[i].left
| Right -> current[i] <- current[i].right
countToEndNode input current ((index + 1) % input.directions.Length) (count + 1L)
let ghostWalk'' (input: ChallengeInput) =
let nodeGraph = buildNodeGraph input
let start = nodeGraph |> Array.filter (fun node -> node.isStartNode)
countToEndNode input start 0 0L
// Note, takes a while to output as it is a cyclic graph
buildNodeGraph sampleInput3
#!fsharp
ghostWalk'' sampleInput3
#!markdown
```f#
ghostWalk'' challengeInput
```
This had not produced a response in over 10 mins. I think the code is about as efficient as I can make it. Lets go to a sequence length approach
#!fsharp
let followDirections' (input: ChallengeInput) (start: string) =
next input 0 start
|> Seq.takeWhile (not << isEndingNode)
let sequenceLengths (input: ChallengeInput) =
input.nodes.Keys
|> Seq.filter (isStartingNode)
|> Seq.map (followDirections' input >> Seq.length)
|> Array.ofSeq
sequenceLengths sampleInput3
#!fsharp
sequenceLengths challengeInput
#!fsharp
let primes = [|
2;3;5;7;11;13;17;19;23;29
31;37;41;43;47;53;59;61;67;71
73;79;83;89;97;101;103;107;109;113
127;131;137;139;149;151;157;163;167;173
179;181;191;193;197;199;211;223;227;229
233;239;241;251;257;263;269;271;277;281
283;293;307;311;313;317;331;337;347;349
353;359;367;373;379;383;389;397;401;409
419;421;431;433;439;443;449;457;461;463
467;479;487;491;499;503;509;521;523;541
547;557;563;569;571;577;587;593;599;601
607;613;617;619;631;641;643;647;653;659
661;673;677;683;691;701;709;719;727;733
739;743;751;757;761;769;773;787;797;809
811;821;823;827;829;839;853;857;859;863
877;881;883;887;907;911;919;929;937;941
947;953;967;971;977;983;991;997;1009;1013
1019;1021;1031;1033;1039;1049;1051;1061;1063;1069
1087;1091;1093;1097;1103;1109;1117;1123;1129;1151
1153;1163;1171;1181;1187;1193;1201;1213;1217;1223
|]
let leastCommonMultiple (input: int array) =
let isDivisibleByPrime (prime: int) (i: int) = i % prime = 0
let nextLayerMap (prime: int) (i: int) =
if isDivisibleByPrime prime i
then i / prime
else i
let folder (layer: int array, result: int64) (prime: int) =
let anyDivisible =
layer
|> Seq.exists (fun i -> i % prime = 0)
if anyDivisible
then
let nextLayer =
layer
|> Array.map (nextLayerMap prime)
(nextLayer, result * int64 prime)
else
(layer, result)
let (finalLayer, p) =
primes
|> Seq.takeWhile (fun x -> input |> Array.forall ((<) x))
|> Seq.fold folder (input, 1)
p * (finalLayer |> Seq.map int64 |> Seq.reduce (*))
let ghostWalk'''' (input: ChallengeInput) =
sequenceLengths input
|> leastCommonMultiple
ghostWalk'''' sampleInput3
#!fsharp
ghostWalk'''' challengeInput
#!markdown
result = 21083806112641