-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday23.cpp
More file actions
617 lines (533 loc) · 20.2 KB
/
day23.cpp
File metadata and controls
617 lines (533 loc) · 20.2 KB
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
#include "day23.h"
#include "helpers.h"
#include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <fstream>
#include <iostream>
#include <unordered_map>
#include <string>
#include <vector>
namespace day23
{
long long solvePart1(std::ifstream& file);
long long solvePart2(std::ifstream& file);
void run_day(bool example)
{
std::cout << "Running day 23 " << (example ? "(example)" : "") << '\n';
const std::string fileName{ example ? "inputs/day23_example.txt" : "inputs/day23_real.txt" };
std::ifstream file{ fileName };
std::cout << "Part 1 answer: " << solvePart1(file) << '\n';
file.close();
file.open(fileName);
std::cout << "Part 2 answer: " << solvePart2(file) << '\n';
}
struct Point
{
int x{};
int y{};
Point operator+(const Point& other) const
{
return Point{ x + other.x, y + other.y };
}
bool operator==(const Point& other) const
{
return x == other.x && y == other.y;
}
bool operator!=(const Point& other) const
{
return !(*this == other);
}
};
struct PointHasher
{
std::size_t operator()(const Point& p) const
{
// bad hash
return static_cast<size_t>(((p.x * 179) + (p.y * 3213)) % 329133);
}
};
// Orders of below two north, east, south, west
std::array<Point, 4> adjacentOffsets{
Point{0, -1},
Point{1, 0},
Point{0, 1},
Point{-1, 0}
};
std::array<char, 4> exitArrows{ '^', '>', 'v', '<' };
bool isArrow(char c)
{
return c == '>' || c == 'v' || c == '<' || c == '^';
}
// Assumption from looking at example & real input:
// Map consists of route segments that end in a choice of two routes
// Probably no loops?
struct Map
{
std::vector < std::string> tiles{};
int height{};
int width{};
void parseInput(std::ifstream& file)
{
while (!file.eof())
{
std::string line;
std::getline(file, line);
tiles.push_back(line);
}
height = static_cast<int>(tiles.size());
width = static_cast<int>(tiles[0].size());
}
[[nodiscard]] char getPos(const Point& p) const
{
if (p.y < 0 || p.y >= height || p.x < 0 || p.x >= width)
{
// Just treat out of bounds as # for simplicity
return '#';
}
return tiles[static_cast<size_t>(p.y)][static_cast<size_t>(p.x)];
}
[[nodiscard]] long long findLongestRoute() const
{
// Find starting tile
Point startPos;
for (size_t x = 0; x < static_cast<size_t>(width); x ++ )
{
if (tiles[0][x] == '.')
{
startPos = Point{ static_cast<int>(x), 0 };
}
}
return findLongestFromPoint(startPos);
}
[[nodiscard]] long long findLongestFromPoint(Point p) const
{
// Assumption here:
// After split/start we're always in a spot with 1 adjacent '.' square
// Follow this finding one new adjacent '.' every step, till we reach a
// '>' or end.
long long moved{};
bool foundNextPoint{ false };
Point nextPointOnPath;
for (const auto& adjacentOffset : adjacentOffsets)
{
const Point option{ p + adjacentOffset };
if (getPos(option) == '.')
{
// Validation 1 adjacent point.
assert(!foundNextPoint);
nextPointOnPath = option;
foundNextPoint = true;
}
}
moved++;
// Follow path till there is an adjacent arrow
// Assumption: don't need to check for bounds of map because map is surrounded by '#'
Point lastPoint{ p };
Point curPoint{ nextPointOnPath };
while (true)
{
if (curPoint.y == (height - 1))
{
// Reached the goal (bottom row)
return moved;
}
foundNextPoint = false;
for (const auto& adjacentOffset : adjacentOffsets)
{
const Point option{ curPoint + adjacentOffset };
if (option != lastPoint && getPos(option) == '.')
{
// Validation 1 adjacent point.
assert(!foundNextPoint);
nextPointOnPath = option;
foundNextPoint = true;
}
}
if (foundNextPoint)
{
moved++;
lastPoint = curPoint;
curPoint = nextPointOnPath;
continue;
}
// If we didn't find '.', look for arrow
bool foundArrow{ false };
for (const auto& adjacentOffset : adjacentOffsets)
{
const Point option{ curPoint + adjacentOffset };
if (option != lastPoint && isArrow(getPos(option)))
{
// Validation 1 adjacent point.
assert(!foundArrow);
// Move an extra square along the arrow
nextPointOnPath = option + adjacentOffset;
foundArrow = true;
}
}
assert(foundArrow);
curPoint = nextPointOnPath;
moved += 2;
break;
}
// Now we are at an intersection
std::vector<Point> exits{};
for (size_t i = 0; i < 4; i++)
{
Point option{ curPoint + adjacentOffsets[i] };
if (getPos(option) == exitArrows[i])
{
// Move second step across the arrow
exits.push_back(option + adjacentOffsets[i]);
}
}
assert(!exits.empty());
moved += 2;
long long maxOfSubPaths{};
for (const auto& exit : exits)
{
maxOfSubPaths = std::max(maxOfSubPaths, findLongestFromPoint(exit));
}
return moved + maxOfSubPaths;
}
};
// Assumption for part two:
// map can be split up in intersections (points with >2 ajacent empty points) & paths inbetween
// Approach is to parse into graph of intersection and pathweight inbetween.
struct Intersection
{
Point pos{};
size_t index{};
std::vector <std::pair<long long, size_t>> adjacentIntersectionIndices{};
bool isStart{};
bool isFinish{};
[[nodiscard]] bool operator==(const Intersection& other) const
{
return pos == other.pos;
}
};
struct PartTwoMap
{
std::vector < std::string> tiles{};
int height{};
int width{};
std::unordered_map<size_t, Intersection> intersectionLookupByIndex{};
size_t intersectionIndex{};
void parseInput(std::ifstream& file)
{
while (!file.eof())
{
std::string line;
std::getline(file, line);
tiles.push_back(line);
}
height = static_cast<int>(tiles.size());
width = static_cast<int>(tiles[0].size());
}
[[nodiscard]] char getPos(const Point& p) const
{
if (p.y < 0 || p.y >= height || p.x < 0 || p.x >= width)
{
// Just treat out of bounds as # for simplicity
return '#';
}
if (tiles[static_cast<size_t>(p.y)][static_cast<size_t>(p.x)] == '#')
{
return '#';
}
// Everything except # is . in part2
return '.';
}
void determineIntersections()
{
// Start by adding start pos
Point startPos;
for (size_t x = 0; x < static_cast<size_t>(width); x++)
{
if (tiles[0][x] == '.')
{
startPos = Point{ static_cast<int>(x), 0 };
}
}
Intersection startIntersection{ startPos };
startIntersection.isStart = true;
startIntersection.index = 0;
intersectionLookupByIndex[0] = startIntersection;
intersectionIndex++;
// Recursively add all intersections to lookup, starting from the startPos
addIntersectionToGraph(intersectionLookupByIndex[0]);
}
void addIntersectionToGraph(const Intersection& intersection)
{
Intersection& intersectionRef{ intersectionLookupByIndex[intersection.index] };
std::vector<Intersection> intersectionsToRecurOn{};
for (auto adjacentOffset : adjacentOffsets)
{
Point option{ adjacentOffset + intersectionRef.pos };
if (getPos(option) == '.')
{
auto result{ followPath(option, intersectionRef.pos) };
// Determine to recur on the found intersection
Intersection i{ result.second };
if (std::ranges::any_of(intersectionLookupByIndex, [i](const std::pair<size_t, Intersection>& p) {return p.second == i; }))
{
const auto existingInter{ *std::ranges::find_if(intersectionLookupByIndex, [i](const std::pair<size_t, Intersection>& p) {return p.second == i; }) };
intersectionRef.adjacentIntersectionIndices.emplace_back(result.first, existingInter.second.index);
continue;
}
i.index = intersectionIndex;
intersectionIndex++;
intersectionLookupByIndex[i.index] = i;
if (i.pos.y == height - 1)
{
// Intersection is end node, don't need to recur from it
// just add directly to lookup
intersectionLookupByIndex[i.index].isFinish = true;
}
else
{
// Is an intersection to recur on
intersectionsToRecurOn.push_back(intersectionLookupByIndex[i.index]);
}
// Add the result to the adjacents of current intersection.
intersectionRef.adjacentIntersectionIndices.emplace_back(result.first, i.index);
}
}
for (auto& i : intersectionsToRecurOn)
{
addIntersectionToGraph(i);
}
}
// Follows a path (until an intersection is reached). Returns the coordinates of the intersection
// and number of steps to reach it from originPoint.
[[nodiscard]] std::pair<long long, Point> followPath(const Point firstPointOnPath, const Point originPoint) const
{
// Repeatedly follow path until we reach a node where non-previous adjacent empty positions != 1.
long long moved{ 1 };
Point lastPoint{ originPoint };
Point curPoint{ firstPointOnPath };
while (true)
{
bool foundNextPoint{false};
Point nextPoint;
bool foundIntersection{ false };
for (const auto& adjacentOffset : adjacentOffsets)
{
const Point option{ curPoint + adjacentOffset };
if (option != lastPoint && getPos(option) == '.')
{
// Validation 1 adjacent point.
if (foundNextPoint)
{
// Found a node with two possible next points, meaning intersection;
foundIntersection = true;
break;
}
nextPoint = option;
foundNextPoint = true;
}
}
if (foundIntersection)
{
break;
}
if (!foundNextPoint)
{
// No next point found, assumption: this only happens at start/end (no other deadends in maze)
assert(curPoint.y == 0 || curPoint.y == width - 1);
break;
}
if (foundNextPoint)
{
moved++;
lastPoint = curPoint;
curPoint = nextPoint;
continue;
}
}
return std::pair{ moved, curPoint };
}
struct searchState
{
size_t intersectionIndex;
long long passedLookup;
long long distance;
};
long long findLongestPathStackBased()
{
std::vector<searchState> stateStack{ searchState{0, 1LL << 0, 0LL}};
long long maxDistanceFound{};
while(!stateStack.empty())
{
searchState state{ stateStack.back() };
stateStack.pop_back();
const auto& intersection{ intersectionLookupByIndex[state.intersectionIndex] };
if (intersection.isFinish)
{
maxDistanceFound = std::max(state.distance, maxDistanceFound);
continue;
}
for (const auto& [distance, adjacentIntersectIndex] : intersection.adjacentIntersectionIndices)
{
const long long bitMask{ 1LL << adjacentIntersectIndex };
if ((state.passedLookup & bitMask) > 1)
{
// already passed in the past of this state
continue;
}
stateStack.emplace_back(
adjacentIntersectIndex,
state.passedLookup | bitMask,
state.distance + distance
);
}
}
return maxDistanceFound;
}
// long long findLongestPathLengthThroughIntersections()
// {
// // naive implementation where we just pass lookup of which intersections we already passed:
//
// // Start by finding start pos
// Point startPos;
// for (size_t x = 0; x < static_cast<size_t>(width); x++)
// {
// if (tiles[0][x] == '.')
// {
// startPos = Point{ static_cast<int>(x), 0 };
// }
// }
//
// std::array<bool, 40> passedLookup{};
// // return longestRecur(startPos, passedLookup);
// return longestRecur(startPos, 0LL);
// }
// // debug version that also returns the points taken in longest path
// std::pair<long long, std::vector<Point>> findLongestPathThroughIntersections()
// {
// // naive implementation where we just pass lookup of which intersections we already passed:
//
// // Start by finding start pos
// Point startPos;
// for (size_t x = 0; x < static_cast<size_t>(width); x++)
// {
// if (tiles[0][x] == '.')
// {
// startPos = Point{ static_cast<int>(x), 0 };
// }
// }
//
// std::array<bool, 40> passedLookup{};
// return longestRecurWithPath(startPos, passedLookup);
// }
//
// // note: 40 is large enough for my input
// long long longestRecur(const Point pos, std::array<bool, 40>& passedLookup)
// {
// const auto& intersection{ intersectionsLookup[pos] };
//
// if (passedLookup[intersection.index])
// {
// // Just large negative to discourage reusing passed intersections.
// return -1000000;
// }
//
// if (intersection.isFinish)
// {
// // End
// return 0;
// }
//
// passedLookup[intersection.index] = true;
//
// long long max{-100000000};
// for (const auto& [distance, adjacentIntersectPos] : intersection.adjacentIntersections)
// {
// max = std::max(max, distance + longestRecur(adjacentIntersectPos, passedLookup));
// }
//
// // Make passedLookup reusable for above in recursion without needing to make copies.
// passedLookup[intersection.index] = false;
// return max;
// }
// // note: 40 is large enough for my input
// long long longestRecur(const Point pos, long long passedLookup)
// {
// const auto& intersection{ intersectionsLookup[pos] };
// const long long bitMask{ 1LL << intersection.index };
//
// if ((passedLookup & bitMask) > 1)
// {
// // Just large negative to discourage reusing passed intersections.
// return -1000000;
// }
//
// if (intersection.isFinish)
// {
// // End
// return 0;
// }
//
// passedLookup |= bitMask;
//
// long long max{ -100000000 };
// for (const auto& [distance, adjacentIntersectPos] : intersection.adjacentIntersections)
// {
// max = std::max(max, distance + longestRecur(adjacentIntersectPos, passedLookup));
// }
//
// // Make passedLookup reusable for above in recursion without needing to make copies.
// return max;
// }
// // debug version that also returns the points taken in longest path
// std::pair<long long, std::vector<Point>> longestRecurWithPath(const Point pos, std::array<bool, 40>& passedLookup)
// {
// const auto& intersection{ intersectionsLookup[pos] };
//
// if (passedLookup[intersection.index])
// {
// // Just large negative to discourage reusing passed intersections.
// return std::pair{ -1000000, std::vector<Point>{intersection.pos} };
// }
//
// if (intersection.isFinish)
// {
// // End
// return std::pair{0, std::vector<Point>{intersection.pos}};
// }
//
// passedLookup[intersection.index] = true;
//
// long long max{-100000000};
// std::vector<Point> longestPath;
// for (const auto& [distance, adjacentIntersectPos] : intersection.adjacentIntersections)
// {
// const auto& [subDist, subPath]{ longestRecurWithPath(adjacentIntersectPos, passedLookup) };
// if (subDist + distance > max)
// {
// max = subDist + distance;
// longestPath = subPath;
// }
// }
//
// // Make passedLookup reusable for above in recursion without needing to make copies.
// passedLookup[intersection.index] = false;
// longestPath.push_back(pos);
// return std::pair{ max, longestPath };
// }
};
long long solvePart1(std::ifstream& file)
{
Map map{};
map.parseInput(file);
return map.findLongestRoute();
}
long long solvePart2(std::ifstream& file)
{
PartTwoMap map{};
map.parseInput(file);
map.determineIntersections();
return map.findLongestPathStackBased();
}
}