From 8c20f2ce7ed3e3ea3ad0ed32a1f94a06f6727fa6 Mon Sep 17 00:00:00 2001 From: TiagoRG Date: Sat, 2 Dec 2023 16:20:10 +0000 Subject: [PATCH] AoC 2023: Day 2 - Also updated to .NET 8.0 Signed-off-by: TiagoRG --- AdventOfCode.csproj | 2 +- Year2023/Day2.cs | 99 ++++++++++++++++++++++++++++++++++++++++++ Year2023/Loader2023.cs | 1 + 3 files changed, 101 insertions(+), 1 deletion(-) create mode 100644 Year2023/Day2.cs diff --git a/AdventOfCode.csproj b/AdventOfCode.csproj index 2b14c81..44344c2 100644 --- a/AdventOfCode.csproj +++ b/AdventOfCode.csproj @@ -2,7 +2,7 @@ Exe - net7.0 + net8.0 enable enable diff --git a/Year2023/Day2.cs b/Year2023/Day2.cs new file mode 100644 index 0000000..ca253a9 --- /dev/null +++ b/Year2023/Day2.cs @@ -0,0 +1,99 @@ +namespace AdventOfCode.Year2023; + +public static class Day2 +{ + private static List Input = File.ReadAllLines("inputs/Year2023/day2.txt").ToList(); + + private class Game + { + public int Id { get; set; } + public List> Sets { get; set; } = new List>(); + } + private static List Games = new List(); + + public static void Run() + { + ParseGames(); + Console.WriteLine($@" +Day2 Solution +Part1 Result: {Part1()} +Part2 Result: {Part2()} + +============================="); + } + + private static int Part1() + { + int sum = 0; + + foreach (var game in Games) + { + foreach (var set in game.Sets) + if (set["red"] > 12 || set["green"] > 13 || set["blue"] > 14) goto cont; + sum += game.Id; + cont: continue; + } + + return sum; + } + + private static int Part2() + { + int sum = 0; + + foreach (var game in Games) + { + Dictionary minimum = new Dictionary { + {"red", 0}, + {"green", 0}, + {"blue", 0} + }; + foreach (var set in game.Sets) + { + foreach (var color in set.Keys) + { + if (minimum[color] < set[color]) minimum[color] = set[color]; + } + } + sum += minimum.Values.ToArray().Product(); + } + + return sum; + } + + private static void ParseGames() + { + foreach (var line in Input) + { + Game game = new Game(); + + string[] game_sets = line.Split(": "); + game.Id = Convert.ToInt32(game_sets[0].Split(" ")[1]); + + string[] sets = game_sets[1].Split("; "); + + foreach (var setStr in sets) + { + Dictionary set = new Dictionary(); + foreach (var color in setStr.Split(", ")) + { + set.Add(color.Split(" ")[1], Convert.ToInt32(color.Split(" ")[0])); + } + if (!set.ContainsKey("red")) set.Add("red", 0); + if (!set.ContainsKey("green")) set.Add("green", 0); + if (!set.ContainsKey("blue")) set.Add("blue", 0); + game.Sets.Add(set); + } + + Games.Add(game); + } + } + + private static int Product(this int[] array) + { + int result = 1; + foreach (var e in array) + result *= e; + return result; + } +} diff --git a/Year2023/Loader2023.cs b/Year2023/Loader2023.cs index d56d0b5..899dbec 100644 --- a/Year2023/Loader2023.cs +++ b/Year2023/Loader2023.cs @@ -11,6 +11,7 @@ public static class Loader2023 */ Day1.Run(); + Day2.Run(); } }