Advent of Code - Day 3

Super cool the Advent of Code - something fun to do in the last 30+ days of the year. Check it out. Two challenges every night for a little over a month: Day 3 - Advent of Code 2020

For day #3, best is to push the input to a list of strings, and then create a function that takes that list, the col and the row, looking for the trees. Some modular math in the middle to account for the infinite cols. First submission failed due to the fact that the product will be larger than Int.Max. Switch to long, and it works. Fun idea. Code is below, no spoillers (won't give away the result). Cheers, ACC.

using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace AdventOfCode
{
    class Program
    {
        static void Main(string[] args)
        {
            FileInfo fi = new FileInfo(args[0]);
            StreamReader sr = fi.OpenText();
            List input = new List();
            while (!sr.EndOfStream)
            {
                string str = sr.ReadLine().Trim();
                if (!String.IsNullOrEmpty(str))
                {
                    input.Add(str);
                }
            }
            sr.Close();

            int[] rowSlope = { 1, 1, 1, 1, 2 };
            int[] colSlope = { 1, 3, 5, 7, 1 };

            long product = 1;
            for (int i = 0; i < rowSlope.Length; i++)
            {
                int result = Process(input, rowSlope[i], colSlope[i]);
                Console.WriteLine("For (r={0}, c={1}) ==> {2}", rowSlope[i], colSlope[i], result);
                product *= result;
            }
            Console.WriteLine(product);
        }

        public static int Process(List input, int rowSlope, int colSlope)
        {
            int trees = 0;

            int col = colSlope;
            int row = rowSlope;
            while(row < input.Count)
            {
                if (input[row][col] == '#') trees++;
                col = (col + colSlope) % input[row].Length;
                row += rowSlope;
            }
            return trees;
        }
    }
}

Comments

Popular posts from this blog

Advent of Code - Day 6, 2024: BFS and FSM

Golang vs. C#: performance characteristics (simple case study)

Advent of Code - Day 7, 2024: Backtracking and Eval