-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaoc-13.1.csx
84 lines (72 loc) · 2.41 KB
/
aoc-13.1.csx
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
using System.Linq;
var caveConnections = File.ReadAllLines(@".\input.13.0.txt")
.Select(line => line.Split('-')).ToArray();
Dictionary<string, List<string>> caveConnectionMap = new();
foreach (var caveConnection in caveConnections)
{
caveConnectionMap.AddOrUpdate(caveConnection[0], caveConnection[1]);
caveConnectionMap.AddOrUpdate(caveConnection[1], caveConnection[0]);
}
var smallCaves = caveConnectionMap.Keys.Where(k => (k != "start" || k != "end") && char.IsLower(k[0]));
var validPaths = new List<string>();
foreach (var caveConnection in caveConnections.Where(c => c.Any(cc => cc == "start")))
{
string startPoint, destPoint;
if (caveConnection[0] == "start")
{
startPoint = caveConnection[0];
destPoint = caveConnection[1];
}
else
{
startPoint = caveConnection[1];
destPoint = caveConnection[0];
}
foreach (var smallCave in smallCaves)
{
MapCavePathway(startPoint, destPoint, smallCave);
}
}
validPaths = validPaths.Distinct().OrderBy(v => v).ToList();
// foreach(var validPath in validPaths)
// {
// System.Console.WriteLine(validPath);
// }
System.Console.WriteLine($"No of valid paths: {validPaths.Count()}");
void MapCavePathway(string path, string destPoint, string smallCaveMultiVisits)
{
var newPathPoint = $",{destPoint}";
var newPath = path + newPathPoint;
if (destPoint == "end")
{
validPaths.Add(newPath);
return;
}
// rules
bool isSmallCave = char.IsLower(destPoint[0]);
if (isSmallCave) // lower case point can only be visited once, except the one on smallCaveMultiVisits parameter it can be visited twice
{
if (smallCaveMultiVisits == destPoint)
{
if (path.Split(',').Count(p => p == destPoint) > 1) return; // stop
}
else if (path.Contains(newPathPoint)) return;
}
if (destPoint == "start") // start points can only be visited once
{
return; // stop
}
if (caveConnectionMap.ContainsKey(destPoint))
{
foreach (var point in caveConnectionMap[destPoint])
{
MapCavePathway(newPath, point, smallCaveMultiVisits);
}
}
}
static void AddOrUpdate(this Dictionary<string, List<string>> targetDictionary, string key, string entry)
{
if (!targetDictionary.ContainsKey(key))
targetDictionary.Add(key, new List<string>());
targetDictionary[key].Add(entry);
}