-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day10.cs
95 lines (77 loc) · 2.87 KB
/
Day10.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
using System.Numerics;
namespace AdventOfCode2023.Puzzle.Day10;
[PuzzleInformation(Name ="Pipe Maze", Day = 10, Complete = true)]
public class Day10 : PuzzleBase<Day10>
{
private static readonly Complex Up = -Complex.ImaginaryOne;
private static readonly Complex Down = Complex.ImaginaryOne;
private static readonly Complex Right = Complex.One;
private static readonly Complex Left = -Complex.One;
private static readonly Complex[] Directions = { Up, Right, Down, Left };
private Dictionary<Complex, char> _map = new();
public Day10() : base("input.txt") { }
public override void Setup()
{
Lines = Utils.Utils.ReadPuzzleLines(10, Filename).ToArray();
var lines = Lines.ToArray();
for (var i = 0; i < lines.Length; i++)
for (var j = 0; j < lines[i].Length; j++)
_map[new Complex(j, i)] = lines[i][j];
}
public override string Part1() => (LoopPositions().Count / 2).ToString();
public override string Part2()
{
var loop = LoopPositions();
var map = (
from entry in _map
let position = entry.Key
let cell = loop.Contains(position) ? entry.Value : '.'
select (position, cell))
.ToDictionary(x => x.position, x => x.cell);
return (map.Keys.Count(position => Inside(map, position))).ToString();
}
private HashSet<Complex> LoopPositions()
{
var current = _map.Keys.Single(x => _map[x] == 'S');
var result = new HashSet<Complex>();
var direction = Directions.First(x => DirectionsIn(_map[current + x]).Contains(x));
while (!result.Contains(current))
{
result.Add(current);
current += direction;
if (_map[current] == 'S')
break;
direction = DirectionsOut(_map[current]).Single(x => x != -direction);
}
return result;
}
private bool Inside(Dictionary<Complex, char> map, Complex position)
{
if (map[position] != '.')
return false;
var result = false;
position--;
while (map.ContainsKey(position))
{
if ("SJL|".Contains(map[position]))
result = !result;
position--;
}
return result;
}
private static IEnumerable<Complex> DirectionsIn(char c) => DirectionsOut(c).Select(c => -c).ToArray();
private static IEnumerable<Complex> DirectionsOut(char c)
{
return c switch
{
'7' => new[] { Left, Down },
'F' => new[] { Right, Down },
'L' => new[] { Up, Right },
'J' => new[] { Up, Left },
'|' => new[] { Up, Down },
'-' => new[] { Left, Right },
'S' => new[] { Up, Down, Left, Right },
_ => Array.Empty<Complex>()
};
}
}