Updated Day 9 rope walker, implemented translation via Math.Sign using the delta between 2 points

This commit is contained in:
Rob Stoffelen 2022-12-15 09:19:19 +01:00
parent cf2a2e1f39
commit 08dbff1008
2 changed files with 8 additions and 44 deletions

View File

@ -12,7 +12,7 @@ D 1
L 5
R 2";
Answerable answerable = new Day10Part2();
Answerable answerable = new Day09Part1();
byte[] dataArray = File.ReadAllBytes(answerable.DefaultInputFile);
//dataArray = Encoding.UTF8.GetBytes(_demoData);

View File

@ -2,29 +2,9 @@
{
internal class VirtualPoint
{
internal int X { get; private set; } = 0;
internal int X { get; set; } = 0;
internal int Y { get; private set; } = 0;
internal void MoveUp()
{
Y++;
}
internal void MoveDown()
{
Y--;
}
internal void MoveRight()
{
X++;
}
internal void MoveLeft()
{
X--;
}
internal int Y { get; set; } = 0;
internal void Translate(int x, int y)
{
@ -35,7 +15,7 @@
internal class RopeWalker
{
private VirtualPoint HeadLocation = new();
private readonly VirtualPoint HeadLocation = new();
private VirtualPoint LastHeadLocation = new();
private VirtualPoint TailLocation = new();
@ -55,7 +35,8 @@
for (int movement = 0; movement < amountToMove; movement++)
{
// set the last pos before moving
LastHeadLocation = HeadLocation;
LastHeadLocation.X = HeadLocation.X;
LastHeadLocation.Y = HeadLocation.Y;
// do the actual move
switch (direction)
@ -67,10 +48,9 @@
}
// check if the tail is touching
if (!IsTailTouchingHead(direction))
if (!IsTailTouchingHead(HeadLocation, TailLocation))
{
// if not, move tail to last head position
TailLocation = LastHeadLocation;
TailLocation.Translate(Math.Sign(HeadLocation.X - TailLocation.X), Math.Sign(HeadLocation.Y - TailLocation.Y));
// add the new position to the list of visited positions
TailVistedLocations.Add($"{TailLocation.X},{TailLocation.Y}");
@ -81,22 +61,6 @@
return TailVistedLocations.Distinct().Count();
}
private bool IsTailTouchingHead(char direction)
{
return direction switch
{
// up; Y + 1
'U' => TailLocation.Y + 1 >= HeadLocation.Y,
// down; Y - 1
'D' => TailLocation.Y - 1 <= HeadLocation.Y,
// right; X + 1
'R' => TailLocation.X + 1 >= HeadLocation.X,
// left; X - 1
'L' => TailLocation.X - 1 <= HeadLocation.X,
_ => throw new AccessViolationException(),
};
}
private bool IsTailTouchingHead(VirtualPoint point1, VirtualPoint point2)
{
return !(Math.Abs(point1.X - point2.X) > 1) && !(Math.Abs(point1.Y - point2.Y) > 1);