-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cs
61 lines (51 loc) · 1.68 KB
/
Solution.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
using System;
using System.Collections.Generic;
using System.Linq;
namespace AdventOfCode2016.Day01
{
internal class Solution
{
private readonly IReadOnlyCollection<(Rotation, int Steps)> _instructions;
public Solution(string input)
{
_instructions = input.Split(", ").Select(ParseInstruction).ToList();
}
public int PartOne()
{
var finalPosition = Traverse().Last();
return finalPosition.ManhattanDistance;
}
public int PartTwo()
{
var visited = new HashSet<IntVector>();
foreach (var position in Traverse())
{
if (!visited.Add(position))
{
return position.ManhattanDistance;
}
}
throw new InvalidOperationException();
}
private IEnumerable<IntVector> Traverse()
{
var position = new IntVector(0, 0);
var direction = Direction.North;
foreach (var (rotation, steps) in _instructions)
{
direction = direction.Turn(rotation);
for (var i = 0; i < steps; i++)
{
position += direction.Move();
yield return position;
}
}
}
private static (Rotation, int Steps) ParseInstruction(string instruction)
{
var rotation = instruction.StartsWith('R') ? Rotation.Right : Rotation.Left;
var steps = int.Parse(instruction[1..]);
return (rotation, steps);
}
}
}