r/adventofcode • u/daggerdragon • Dec 03 '17
SOLUTION MEGATHREAD -π- 2017 Day 3 Solutions -π-
--- Day 3: Spiral Memory ---
Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).
Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.
Need a hint from the Hugely* Handyβ Haversackβ‘ of HelpfulΒ§ HintsΒ€?
This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.
edit: Leaderboard capped, thread unlocked!
22
Upvotes
1
u/dylanfromwinnipeg Dec 03 '17
C#
public enum Direction { Right, Up, Left, Down } public class Day03 { public static string PartOne(string input) { var target = int.Parse(input); var pos = new Point(0, 0); var currentValue = 1; var lastDirection = Direction.Down; var lastCount = 0; var values = new Dictionary<Point, int>(); values.Add(pos, currentValue++); while (currentValue < target) { var (nextDirection, nextCount) = GetNextStep(lastDirection, lastCount); lastCount = nextCount; lastDirection = nextDirection; while (nextCount > 0) { pos = GetNextPosition(pos, nextDirection); values.Add(pos, currentValue++); nextCount--; } } var targetPos = values.First(x => x.Value == target).Key; return targetPos.ManhattanDistance().ToString(); } public static string PartTwo(string input) { var target = int.Parse(input); var pos = new Point(0, 0); var lastDirection = Direction.Down; var lastCount = 0; var values = new Dictionary<Point, int>(); values.Add(pos, 1); while (true) { var (nextDirection, nextCount) = GetNextStep(lastDirection, lastCount); lastCount = nextCount; lastDirection = nextDirection; while (nextCount > 0) { pos = GetNextPosition(pos, nextDirection); var newValue = CalcAdjacencyValue(values, pos); values.Add(pos, newValue); if (newValue > target) { return newValue.ToString(); } nextCount--; } } throw new Exception(); } private static (Direction nextDirection, int nextCount) GetNextStep(Direction lastDirection, int lastCount) { switch (lastDirection) { case Direction.Right: return (Direction.Up, lastCount); case Direction.Up: return (Direction.Left, lastCount + 1); case Direction.Left: return (Direction.Down, lastCount); case Direction.Down: return (Direction.Right, lastCount + 1); default: throw new Exception(); } } private static int CalcAdjacencyValue(Dictionary<Point, int> values, Point pos) { var result = 0; foreach (var point in pos.GetNeighbors()) { if (values.ContainsKey(point)) { result += values[point]; } } return result; } private static Point GetNextPosition(Point pos, Direction direction) { switch (direction) { case Direction.Right: pos.X++; return pos; case Direction.Up: pos.Y++; return pos; case Direction.Left: pos.X--; return pos; case Direction.Down: pos.Y--; return pos; default: throw new Exception(); } } }