Advent of Code 2021: Day 5, part 1

Photo by Fab Lentz on Unsplash

Advent of Code 2021: Day 5, part 1

More 2D array fun

I forgot about my friend Tuple. I didn't want to create a class to bundle my two points together from the parsing of the input file and Tuple is an easy way to get this done.

This challenge was not too difficult for me as Day 4 helped me get in mental shape to deal with 2D arrays.

The most difficult part was understanding the requirements. I kept looking at the points and they did not match up with the visual representation of the lines. This is because you are supposed to IGNORE the points that are diagonals for the first part. This test input is going to be used for the second part.

I wonder what part 2 will bring....?

   public int Day5Part1(List<Tuple<Point,Point>> points )
        {

            var m = new MatrixLineTracking(true);

            foreach(var p in points)
            {
                m.MarkLine(p.Item1, p.Item2);
            }

            return m.IntersectionCount;
        }

    }

    public class Point
    {
        public int X { get; set; }
        public int Y { get; set; }
        public Point(int iX, int iY)
        {
            X = iX;
            Y = iY;
        }
    }

    public class MatrixLineTracking
    {
        private int[,] _matrix;
        private bool _HorizontalVerticalOnly;
        public int IntersectionCount { get; set; }

        public MatrixLineTracking(bool HorizontalVerticalOnly)
        {
            _HorizontalVerticalOnly = HorizontalVerticalOnly;
            _matrix = new int[1000,1000];
        }

        public void MarkLine(Point A, Point B)
        {
            if (A.X == B.X)
            {
                if (A.Y > B.Y)
                {
                    for (int i = A.Y; i >= B.Y; i--)
                    {
                        _matrix[A.X, i]++;
                        if (_matrix[A.X, i] == 2) { IntersectionCount++; }
                    }
                }
                else
                {
                    for (int i = A.Y; i <= B.Y; i++)
                    {
                        _matrix[A.X, i]++;
                        if (_matrix[A.X, i] == 2) { IntersectionCount++; }
                    }
                }
            }
            else if (A.Y == B.Y)
            {
                if (A.X > B.X)
                {
                    for (int i = A.X; i >= B.X; i--)
                    {
                        _matrix[i, A.Y]++;
                        if (_matrix[i, A.Y] == 2) { IntersectionCount++; }
                    }
                }
                else
                {
                    for (int i = A.X; i <= B.X; i++)
                    {
                        _matrix[i, A.Y]++;
                        if (_matrix[i, A.Y] == 2) { IntersectionCount++; }
                    }
                }
            }
        }