Nighed

joined 2 years ago
MODERATOR OF
[–] Nighed@sffa.community 2 points 2 years ago

C# Recursion Time! (max depth 24)

Today I learnt how to get multiple captures out of the same group in Regex. I also learnt how much a console line write slows down your app.... (2 seconds without, never finished with)

Task1

internal class Day4Task1 : IRunnable
    {
        public void Run()
        {
            var inputLines = File.ReadAllLines("Days/Four/Day4Input.txt");
            var regex = new Regex("Card\\s*\\d*: ([\\d\\s]{2} )*\\|( [\\d\\s]{2})*");
            int sumScore = 0;

            foreach (var line in inputLines)
            {
                int lineScore = 0;
                var winningSet = new HashSet();
                var matches = regex.Match(line);
                foreach(Capture capture in matches.Groups[1].Captures) {
                    
                    winningSet.Add(capture.Value.Trim());
                }

                foreach (Capture capture in matches.Groups[2].Captures)
                {
                    if(winningSet.Contains(capture.Value.Trim()))
                    {
                        lineScore = lineScore == 0 ? 1 : lineScore * 2;
                    }
                }

                sumScore += lineScore;
                Console.WriteLine(lineScore.ToString());

            }

            Console.WriteLine("Sum:"+sumScore.ToString());
        }
    }

Task2

internal class Day4Task2 : IRunnable
    {
        private Regex _regex = new Regex("Card\\s*\\d*: ([\\d\\s]{2} )*\\|( [\\d\\s]{2})*");
        private Dictionary _matchCountCache = new Dictionary();
        private int _maxDepth = 0;

        public void Run()
        {
            var inputLines = File.ReadAllLines("Days/Four/Day4Input.txt");
            int sumScore = 0;

            for (int i = 0; i < inputLines.Length; i++)
            {
                sumScore += ScoreCard(i, inputLines, 0);
                Console.WriteLine("!!!" + i + "!!!");
            }

            Console.WriteLine("Sum:"+sumScore.ToString());
            Console.WriteLine("Max Recursion Depth:"+ _maxDepth.ToString());
        }

        private int ScoreCard(int lineId, string[] inputLines, int depth)
        {
            if( depth > _maxDepth )
            {
                _maxDepth = depth;
            }

            if(lineId >= inputLines.Length)
            {
                return 0;
            }

            int matchCount = 0;

            if (!_matchCountCache.ContainsKey(lineId)) {

                var winningSet = new HashSet();
                var matches = _regex.Match(inputLines[lineId]);
                foreach (Capture capture in matches.Groups[1].Captures)
                {
                    winningSet.Add(capture.Value.Trim());
                }

                foreach (Capture capture in matches.Groups[2].Captures)
                {
                    if (winningSet.Contains(capture.Value.Trim()))
                    {
                        matchCount++;
                    }
                }

                _matchCountCache[lineId] = matchCount;
            }

            matchCount = _matchCountCache[lineId];

            int totalCards = 1;
            while(matchCount > 0)
            {
                totalCards += ScoreCard(lineId+matchCount, inputLines, depth+1);
                matchCount--;
            }
            //Console.WriteLine("Finished processing id: " + lineId + " Sum is: " + totalCards);
            return totalCards;
        }
    }

[–] Nighed@sffa.community 4 points 2 years ago (2 children)

However, they are appealing the judgement.

[–] Nighed@sffa.community 1 points 2 years ago

Most people have no idea

[–] Nighed@sffa.community 3 points 2 years ago

Which model was it that overheats in the gulf because the water is too warm?

[–] Nighed@sffa.community 4 points 2 years ago (1 children)

It can't go above 9% of salary though. Treat it like a tax unfortunately.

[–] Nighed@sffa.community 3 points 2 years ago* (last edited 2 years ago)

Language: C#

I aimed at keeping it as simple and short as reasonably possible this time, no overbuilding here!

I even used a goto to let me break out of multiple loops at once 🤮 (I had to look up how they worked!) I would totally fail me in a code review!

One solution for both

internal class Day3 : IRunnable
    {
        public void Run()
        {
            var input = File.ReadAllLines("Days/Three/Day3Input.txt");
            int sum = 0;
            string numStr = "";
            var starMap = new Dictionary<(int,int),List>();
            for (int i = 0; i < input.Length; i++)           
                for (int j = 0; j < input[i].Length; j++)
                {
                    if (char.IsDigit(input[i][j]))                    
                        numStr += input[i][j];                    
                    if (numStr.Length > 0 && (j == input[i].Length - 1 || !char.IsDigit(input[i][j + 1])))
                    {
                        for (int k = Math.Max(0, i - 1); k < Math.Min(i + 2, input.Length); k++)                        
                            for (int l = Math.Max(0, j - numStr.Length); l < Math.Min(j + 2, input[i].Length); l++)                            
                                if (!char.IsDigit(input[k][l]) && input[k][l] != '.')
                                {
                                    sum += int.Parse(numStr);
                                    if (input[k][l] == '*')
                                    {
                                        if (starMap.ContainsKey((k, l)))                                        
                                            starMap[(k, l)].Add(int.Parse(numStr));                                        
                                        else
                                            starMap.Add((k,l),new List { int.Parse(numStr) });
                                    }
                                    goto endSymbSearch;
                                }                           
                    endSymbSearch:
                        numStr = "";
                    }
                }            
            Console.WriteLine("Result1:"+sum.ToString());
            Console.WriteLine("Result2:" + starMap.Where(sm => sm.Value.Count == 2).Sum(sm => sm.Value[0] * sm.Value[1]));
        }
    }

[–] Nighed@sffa.community 3 points 2 years ago* (last edited 2 years ago)

Done in C# Input parsing done with a mixture of splits and Regex (no idea why everyone hates it?) capture groups.

I have overbuilt for both days, but not tripped on any of the 'traps' in the input data - generally expecting the input to be worse than it is... too used to actual data from users

Input Parsing (common)

public class Day2RoundInput { private Regex gameNumRegex = new Regex("[a-z]* ([0-9]*)", RegexOptions.IgnoreCase);

    public Day2RoundInput(string gameString)
    {
        var colonSplit = gameString.Trim().Split(':', StringSplitOptions.RemoveEmptyEntries);
        var match = gameNumRegex.Match(colonSplit[0].Trim());
        var gameNumberString = match.Groups[1].Value;
        GameNumber = int.Parse(gameNumberString.Trim());

        HandfulsOfCubes = new List();
        var roundsSplit = colonSplit[1].Trim().Split(';', StringSplitOptions.RemoveEmptyEntries);
        foreach (var round in roundsSplit)
        {
            HandfulsOfCubes.Add(new HandfulCubes(round));
        }
    }
    public int GameNumber { get; set; }

    public List HandfulsOfCubes { get; set; }

    public class HandfulCubes
    {
        private Regex colourRegex = new Regex("([0-9]*) (red|green|blue)");

        public HandfulCubes(string roundString)
        {
            var colourCounts = roundString.Split(',', StringSplitOptions.RemoveEmptyEntries);
            foreach (var colour in colourCounts)
            {
                var matches = colourRegex.Matches(colour.Trim());

                foreach (Match match in matches)
                {
                    var captureOne = match.Groups[1];

                    var count = int.Parse(captureOne.Value.Trim());

                    var captureTwo = match.Groups[2];

                    switch (captureTwo.Value.Trim().ToLower())
                    {
                        case "red":
                            RedCount = count;
                            break;
                        case "green":
                            GreenCount = count;
                            break;
                        case "blue":
                            BlueCount = count;
                            break;
                        default: throw new Exception("uh oh");
                    }
                }
            }
        }

        public int RedCount { get; set; }
        public int GreenCount { get; set; }
        public int BlueCount { get; set; }
    }

}

Task1internal class Day2Task1:IRunnable { public void Run() { var inputs = GetInputs();

        var maxAllowedRed = 12;
        var maxAllowedGreen = 13;
        var maxAllowedBlue = 14;

        var allowedGameIdSum = 0;

        foreach ( var game in inputs ) { 
            var maxRed = game.HandfulsOfCubes.Select(h => h.RedCount).Max();
            var maxGreen = game.HandfulsOfCubes.Select(h => h.GreenCount).Max();
            var maxBlue = game.HandfulsOfCubes.Select(h => h.BlueCount).Max();

            if ( maxRed <= maxAllowedRed && maxGreen <= maxAllowedGreen && maxBlue <= maxAllowedBlue) 
            {
                allowedGameIdSum += game.GameNumber;
                Console.WriteLine("Game:" + game.GameNumber + " allowed");
            }
            else
            {
                Console.WriteLine("Game:" + game.GameNumber + "not allowed");
            }
        }

        Console.WriteLine("Sum:" + allowedGameIdSum.ToString());

    }

    private List GetInputs()
    {
        List inputs = new List();

        var textLines = File.ReadAllLines("Days/Two/Day2Input.txt");

        foreach (var line in textLines)
        {
            inputs.Add(new Day2RoundInput(line));
        }

        return inputs;
    }

    
}

Task2internal class Day2Task2:IRunnable { public void Run() { var inputs = GetInputs();

        var result = 0;

        foreach ( var game in inputs ) {
            var maxRed = game.HandfulsOfCubes.Select(h => h.RedCount).Max();
            var maxGreen = game.HandfulsOfCubes.Select(h => h.GreenCount).Max();
            var maxBlue = game.HandfulsOfCubes.Select(h => h.BlueCount).Max();

            var power = maxRed*maxGreen*maxBlue;
            Console.WriteLine("Game:" + game.GameNumber + " Result:" + power.ToString());

            result += power;
        }

        Console.WriteLine("Day2 Task2 Result:" + result.ToString());

    }

    private List GetInputs()
    {
        List inputs = new List();

        var textLines = File.ReadAllLines("Days/Two/Day2Input.txt");
        //var textLines = File.ReadAllLines("Days/Two/Day2ExampleInput.txt");

        foreach (var line in textLines)
        {
            inputs.Add(new Day2RoundInput(line));
        }

        return inputs;
    }

    
}

[–] Nighed@sffa.community 3 points 2 years ago

Thank you for this! I always find out/remember about it half way through...

First day done and work leaderboard link shared!

[–] Nighed@sffa.community 7 points 2 years ago* (last edited 2 years ago)

Mad cow disease can (sometimes/possibly) take decades to have an effect. If you are some infected meat and have the wrong genetics you could wind up with a sponge for a brain 30 years later.

Prions are terrifying.

[–] Nighed@sffa.community 2 points 2 years ago

How many people can't finance that though, they are going to be on a ridiculously high interest loan that will way outstrip the fuel savings.

The second hand market won't be there for years (you can get a just about works petrol car ridiculously cheap) and who knows what their batteries will be like at that point

[–] Nighed@sffa.community 1 points 2 years ago

Good point, just delete the second paragraph...

[–] Nighed@sffa.community 1 points 2 years ago

I'm going to say that if you can charge at home, then electric cars are awesome, otherwise a HFC style car might be better.

Both are going to require significant infrastructure build out, but electric chargers are much easier to install.

view more: ‹ prev next ›