-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathYear2018Day20.cs
110 lines (99 loc) · 2.31 KB
/
Year2018Day20.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using AdventOfCode.Common;
using JetBrains.Annotations;
using RoyT.AStar;
namespace AdventOfCode.Solutions._2018._20;
[UsedImplicitly]
public class Year2018Day20 : ISolution
{
public object Part1(IEnumerable<string> input)
{
var paths = input.First()[1..^1];
var (x, y) = (5000, 5000);
var positions = new Stack<(int x, int y)>();
var (prevX, prevY) = (x, y);
var distances = new Dictionary<(int x, int y), int>();
var directions = new Dictionary<char, (int x, int y)>
{
['N'] = (0, -1),
['E'] = (1, 0),
['S'] = (0, 1),
['W'] = (-1, 0)
};
foreach (var c in paths)
{
switch (c)
{
case '(':
positions.Push((x, y));
break;
case ')':
(x, y) = positions.Pop();
break;
case '|':
(x, y) = positions.First();
break;
default:
{
var (dx, dy) = directions[c];
x += dx;
y += dy;
if (distances.ContainsKey((x, y)))
distances[(x, y)] = Math.Min(distances[(x, y)], distances[(prevX, prevY)] + 1);
else
distances[(x, y)] = distances.GetValueOrDefault((prevX, prevY), 0) + 1;
break;
}
}
(prevX, prevY) = (x, y);
}
return distances.Values.Max().ToString();
}
public object Part2(IEnumerable<string> input)
{
var paths = input.First()[1..^1];
var (x, y) = (5000, 5000);
var positions = new Stack<(int x, int y)>();
var (prevX, prevY) = (x, y);
var distances = new Dictionary<(int x, int y), int>();
var directions = new Dictionary<char, (int x, int y)>
{
['N'] = (0, -1),
['E'] = (1, 0),
['S'] = (0, 1),
['W'] = (-1, 0)
};
foreach (var c in paths)
{
switch (c)
{
case '(':
positions.Push((x, y));
break;
case ')':
(x, y) = positions.Pop();
break;
case '|':
(x, y) = positions.First();
break;
default:
{
var (dx, dy) = directions[c];
x += dx;
y += dy;
if (distances.ContainsKey((x, y)))
distances[(x, y)] = Math.Min(distances[(x, y)], distances[(prevX, prevY)] + 1);
else
distances[(x, y)] = distances.GetValueOrDefault((prevX, prevY), 0) + 1;
break;
}
}
(prevX, prevY) = (x, y);
}
return distances.Values.Count(dist => dist >= 1000).ToString();
}
}