public Dist2 Move(Walk w) { Dist2 d2 = new Dist2 { x = x, y = y }; switch (w.dir) { case Directions.North: d2.y -= w.steps; return(d2); case Directions.East: d2.x += w.steps; return(d2); case Directions.South: d2.y += w.steps; return(d2); case Directions.West: d2.x -= w.steps; return(d2); default: throw new NotImplementedException(); } }
public static Dist2 operator +(Dist2 d2, Directions dir) { Dist2 d22 = new Dist2 { x = d2.x, y = d2.y }; switch (dir) { case Directions.North: d22.y--; return(d22); case Directions.East: d22.x++; return(d22); case Directions.South: d22.y++; return(d22); case Directions.West: d22.x--; return(d22); default: throw new NotImplementedException(); } }
public static void Run() { string[] strs = INPUT.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries); List <Walk> walks = strs.Aggregate(new List <Walk>(strs.Length), (ws, str) => { ws.Add(new Walk(ws.LastOrDefault(), str)); return(ws); }); // Part 1 Dist2 part1 = walks.Aggregate(new Dist2 { x = 0, y = 0 }, (d2, w) => d2.Move(w)); Console.WriteLine("==== Part 1 ===="); Console.WriteLine($"X: {part1.x}"); Console.WriteLine($"Y: {part1.y}"); Console.WriteLine($"Total distance: {Math.Abs(part1.x) + Math.Abs(part1.y)}"); // Part 2 Dist2 part2 = Part2(walks); Console.WriteLine("==== Part 2 ===="); Console.WriteLine($"X: {part2.x}"); Console.WriteLine($"Y: {part2.y}"); Console.WriteLine($"Total distance: {Math.Abs(part2.x) + Math.Abs(part2.y)}"); }
private static Dist2 Part2(List <Walk> walks) { HashSet <Dist2> visited = new HashSet <Dist2>(); Dist2 part2 = new Dist2 { x = 0, y = 0 }; foreach (var walk in walks) { foreach (var i in Enumerable.Range(0, walk.steps)) { if (!visited.Add(part2 = part2 + walk.dir)) { return(part2); } } } return(part2); }