From 8ccd370cf528b63a84fcf87a98aca672572c15a6 Mon Sep 17 00:00:00 2001 From: Alex Thomassen Date: Fri, 2 Dec 2022 16:46:35 +0100 Subject: [PATCH] Separate day 1 logic --- Handlers/Day01.cs | 39 ++++++++++++++++++++++++ Program.cs | 77 +++++++++++++++-------------------------------- 2 files changed, 64 insertions(+), 52 deletions(-) create mode 100644 Handlers/Day01.cs diff --git a/Handlers/Day01.cs b/Handlers/Day01.cs new file mode 100644 index 0000000..9b6becc --- /dev/null +++ b/Handlers/Day01.cs @@ -0,0 +1,39 @@ +namespace AdventOfCode2022.Handlers +{ + public class Day01 + { + string[] elves; + IEnumerable caloriesPerElf; + + public Day01() + { + var lines = System.IO.File.ReadAllText(@"./days/01/input"); + elves = lines.Split("\n\n"); + caloriesPerElf = elves.Select(ParseCalories); + + PartA(); + PartB(); + } + + private int ParseCalories(string elf) + { + return elf.Split("\n") + .Where(calorie => !string.IsNullOrWhiteSpace(calorie)) + .Select(int.Parse) + .Sum(); + } + + + public void PartA() + { + var max = caloriesPerElf.Max(); + Console.WriteLine($"Highest calories: {max}"); + } + + public void PartB() + { + var topThree = caloriesPerElf.OrderByDescending(calories => calories).Take(3).Sum(); + Console.WriteLine($"Top three calories: {topThree}"); + } + } +} \ No newline at end of file diff --git a/Program.cs b/Program.cs index 2b187ae..b5dd34b 100644 --- a/Program.cs +++ b/Program.cs @@ -1,53 +1,26 @@ -namespace AdventOfCode2022 -{ - internal class Program - { - static void Main(string[] args) - { - try { - dayOne(); - } - catch (Exception e) { - Console.WriteLine(e.Message); - } - } - - static void PrintSeparator() - { - Console.WriteLine("========================================"); - } - - static void dayOne() { - Console.WriteLine("Day 1"); - // Assumes you're running the binary from the project root - var lines = System.IO.File.ReadAllText(@"./days/01/input"); - var split = lines.Split("\n\n"); - - List allCalories = new List(); - - foreach (var elf in split) { - var rawCalories = elf.Split("\n"); - - int calories = 0; - foreach (var food in rawCalories) { - if (string.IsNullOrWhiteSpace(food)) { - continue; - } - - calories += int.Parse(food.Trim()); - } - - allCalories.Add(calories); - } - - allCalories.Sort(); - allCalories.Reverse(); - - var topThree = allCalories.Take(3).Sum(); - - Console.WriteLine($"Highest calories: {allCalories.First()}"); - Console.WriteLine($"Top three calories: {topThree}"); - PrintSeparator(); - } - } +using AdventOfCode2022.Handlers; +namespace AdventOfCode2022 +{ + internal class Program + { + static void Main(string[] args) + { + try { + dayOne(); + } + catch (Exception e) { + Console.WriteLine(e.Message); + } + } + + static void PrintSeparator() + { + Console.WriteLine("========================================"); + } + + static void dayOne() { + new Day01(); + PrintSeparator(); + } + } } \ No newline at end of file