Skip to content

Instantly share code, notes, and snippets.

@tslater2006
Created December 9, 2022 16:45
Show Gist options
  • Save tslater2006/976add97247eee810eb9f6963ea01687 to your computer and use it in GitHub Desktop.
Save tslater2006/976add97247eee810eb9f6963ea01687 to your computer and use it in GitHub Desktop.
Advent of Code Day 9 Rope
class Rope
{
public HashSet<Point> VisitedPoints = new HashSet<Point>();
Point[] knots;
public Rope(int knotCount)
{
knots = new Point[knotCount];
for(var x = 0; x < knotCount; x++)
{
knots[x] = new Point(0,0);
}
VisitedPoints.Add(knots[0]);
}
public void MoveHead(char direction, int count)
{
for (var x = 0; x < count; x++)
{
switch (direction)
{
case 'U':
knots[0].Y++;
break;
case 'D':
knots[0].Y--;
break;
case 'L':
knots[0].X--;
break;
case 'R':
knots[0].X++;
break;
}
UpdateKnots();
}
}
void UpdateKnots()
{
for (var i = 1; i < knots.Length; i++)
{
if (knots[i-1].X == knots[i].X && Math.Abs(knots[i - 1].Y - knots[i].Y) == 2)
{
/* move towards head */
knots[i].Y += (knots[i - 1].Y - knots[i].Y) / 2;
continue;
}
if (knots[i - 1].Y == knots[i].Y && Math.Abs(knots[i - 1].X - knots[i].X) == 2)
{
/* move towards head */
knots[i].X += (knots[i - 1].X - knots[i].X) / 2;
continue;
}
/* we must be diagonal */
if (Math.Abs(knots[i - 1].X - knots[i].X) + Math.Abs(knots[i - 1].Y - knots[i].Y) >= 3)
{
/* figure out relative direction from tail to head */
knots[i].X += (knots[i - 1].X - knots[i].X) > 0 ? 1 : -1;
knots[i].Y += (knots[i - 1].Y - knots[i].Y) > 0 ? 1 : -1;
continue;
}
}
VisitedPoints.Add(knots[knots.Length - 1]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment