Created
April 1, 2020 15:36
-
-
Save ceilingfish/eb37f83959a54f4ee0c1d9cbd74733b7 to your computer and use it in GitHub Desktop.
Tom's answer to april 1st dev hour
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <Query Kind="Program" /> | |
| void Main() | |
| { | |
| var input = @"5 5 | |
| 1 2 N | |
| LMLMLMLMM | |
| 3 3 E | |
| MMRMMRMRRM"; | |
| var north = new Heading("N", p => p.Y++); | |
| var east = new Heading("E", p => p.X++); | |
| var south = new Heading("S", p => p.Y--); | |
| var west = new Heading("W", p => p.X--); | |
| west.Right = east.Left = north; | |
| north.Right = south.Left = east; | |
| east.Right = west.Left = south; | |
| south.Right = north.Left = west; | |
| var headings = new[] { north, east, south, west }; | |
| var lines = input.Split(new[] {'\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); | |
| var dimensions = lines[0] | |
| .Split(' ') | |
| .Select(s => int.Parse(s.Trim())) | |
| .ToArray(); | |
| var top = dimensions[0]; | |
| var left = dimensions[1]; | |
| for (int i = 1; i < lines.Length; i += 2) | |
| { | |
| var positionText = lines[i]; | |
| var position = RoverPosition.Parse(positionText); | |
| var instructionText = lines[i+1]; | |
| foreach(var instruction in instructionText) | |
| { | |
| var currentHeading = headings.Single(s => s.Name == position.Heading); | |
| switch(instruction) | |
| { | |
| case 'L': | |
| position.Heading = currentHeading.Left.Name; | |
| break; | |
| case 'R': | |
| position.Heading = currentHeading.Right.Name; | |
| break; | |
| case 'M': | |
| currentHeading.Forward(position); | |
| if (position.X < 0) position.X = 0; | |
| if (position.X > left) position.X = left; | |
| if (position.Y < 0) position.Y = 0; | |
| if (position.Y > top) position.Y = top; | |
| break; | |
| } | |
| } | |
| position.ToString().Dump(); | |
| } | |
| } | |
| class Heading | |
| { | |
| public string Name { get; } | |
| public Heading Left { get; set; } | |
| public Heading Right { get; set; } | |
| public Action<RoverPosition> Forward { get; } | |
| public Heading(string name, Action<RoverPosition> forwardAction) | |
| { | |
| Name = name; | |
| Forward = forwardAction; | |
| } | |
| } | |
| class RoverPosition | |
| { | |
| public int X { get; set; } | |
| public int Y { get; set; } | |
| public string Heading { get; set; } | |
| public static RoverPosition Parse(string input) | |
| { | |
| var parts = input.Split(' '); | |
| var position = new RoverPosition | |
| { | |
| X = int.Parse(parts[0]), | |
| Y = int.Parse(parts[1]), | |
| Heading = parts[2] | |
| }; | |
| return position; | |
| } | |
| public override string ToString() => $"{X} {Y} {Heading}"; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment