From d999774ec107dbce0f0f03c64a0d9d765cd9e818 Mon Sep 17 00:00:00 2001 From: TiagoRG Date: Mon, 4 Dec 2023 17:28:27 +0000 Subject: [PATCH] [2023] Finish Day4 - Yes, did skip day 3 :skull: Signed-off-by: TiagoRG --- Year2023/Day4.cs | 67 ++++++++++++++++++++++++++++++++++++++++++ Year2023/Loader2023.cs | 1 + 2 files changed, 68 insertions(+) create mode 100644 Year2023/Day4.cs diff --git a/Year2023/Day4.cs b/Year2023/Day4.cs new file mode 100644 index 0000000..2a46647 --- /dev/null +++ b/Year2023/Day4.cs @@ -0,0 +1,67 @@ +using System.Text.RegularExpressions; + +namespace AdventOfCode.Year2023; + +public static class Day4 +{ + private class Card + { + public int CardNumber { get; set; } + public int[]? WinningNumbers { get; set; } + public int[]? Numbers { get; set; } + public int ValidNumbers { get; set; } + } + + private static List Cards = new(); + private static double Sum; + + public static void Run() + { + File.ReadAllLines("inputs/Year2023/day4.txt").ToList().ForEach(line => + { + Card card = new Card(); + card.CardNumber = Convert.ToInt32(Regex.Split(line.Split(": ")[0], @"\s+").Last()); + string[] cardNumbers = Regex.Split(line.Split(": ")[1], @"\s+\|\s+"); + card.WinningNumbers = Regex.Split(cardNumbers.First(), @"\W+").Where(x => !string.IsNullOrEmpty(x)).Select(x => Convert.ToInt32(x)).ToArray(); + card.Numbers = Regex.Split(cardNumbers.Last(), @"\W+").Where(x => !string.IsNullOrEmpty(x)).Select(x => Convert.ToInt32(x)).ToArray(); + Cards.Add(card); + }); + + Cards.ForEach(card => + { + card.ValidNumbers = 0; + card.Numbers!.ToList().ForEach(number => card.ValidNumbers += card.WinningNumbers!.Contains(number) ? 1 : 0); + }); + + Console.WriteLine($@" +Day4 Solution +Part1 Result: {Part1()} +Part2 Result: {Part2()} + +============================="); + } + + private static double Part1() + { + Sum = 0; + Cards.ForEach(card => Sum += card.ValidNumbers > 0 ? Math.Pow(2, card.ValidNumbers - 1) : 0); + return Sum; + } + + private static double Part2() + { + Sum = 0; + + Dictionary CardInstances = new(); + Cards.ForEach(card => CardInstances.Add(card.CardNumber, 1)); + Cards.ForEach(card => + { + for (int i = card.CardNumber + 1; i <= card.CardNumber + card.ValidNumbers; i++) + CardInstances[i] += CardInstances[card.CardNumber]; + + Sum += CardInstances[card.CardNumber]; + }); + + return Sum; + } +} diff --git a/Year2023/Loader2023.cs b/Year2023/Loader2023.cs index 899dbec..402d7c1 100644 --- a/Year2023/Loader2023.cs +++ b/Year2023/Loader2023.cs @@ -12,6 +12,7 @@ public static class Loader2023 Day1.Run(); Day2.Run(); + Day4.Run(); } }