Refactor, add day 1 puzzle 2

This commit is contained in:
Laura Hausmann 2022-12-01 15:49:53 +01:00
parent 957616ac55
commit 8fc195943b
Signed by: zotan
GPG key ID: D044E84C5BE01605
4 changed files with 17 additions and 16 deletions

16
AoC2022.Day1/Program.cs Normal file
View file

@ -0,0 +1,16 @@
var input = File.ReadAllText("../../../../inputs/1_1.txt").TrimEnd('\n').Split("\n\n"); // Read input file, remove trailing newlines, split by double newline
var elves = input.Select(s => new Elf(s.Split("\n").Select(int.Parse))); // Use LINQ magic (select) to transform the collection of strings into a collection of Elves
Console.WriteLine(elves.MaxBy(elf => elf.Total())!.Total()); // Output Elf with highest total number of calories
Console.WriteLine(elves.OrderByDescending(elf => elf.Total()).Take(3).Sum(elf => elf.Total())); // Output total calories carried by top 3 elves
internal class Elf {
// Elves have a list of calories (technically a list of consumables that each have a calorie value but that distinction doesn't appear to be relevant yet
private readonly List<int> _calories;
// LINQ shenanigans to easily get the sum of these calorie values
public int Total() => _calories.Sum();
// .ToList() because .Select() gives back an IEnumerable and not a List
public Elf(IEnumerable<int> calories) => _calories = calories.ToList();
}

View file

@ -1,15 +0,0 @@
var input = File.ReadAllText("inputs/1_1.txt").TrimEnd('\n').Split("\n\n"); // Read input file, remove trailing newlines, split by double newline
var elves = input.Select(s => new Elf(s.Split("\n").Select(int.Parse))); // Use LINQ magic (select) to transform the collection of strings into a collection of Elves
Console.WriteLine(elves.MaxBy(elf => elf.Total())!.Total()); // Output Elf with highest total number of calories
internal class Elf {
// Elves have a list of calories (technically a list of consumables that each have a calorie value but that distinction doesn't appear to be relevant yet
private readonly List<int> _calories;
// LINQ shenanigans to easily get the sum of these calorie values
public int Total() => _calories.Sum();
// .ToList() because .Select() gives back an IEnumerable and not a List
public Elf(IEnumerable<int> calories) => _calories = calories.ToList();
}

View file

@ -1,6 +1,6 @@

Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AoC2022.Day1_1", "AoC2022.Day1_1\AoC2022.Day1_1.csproj", "{620896E5-2412-4713-BA7B-ABB66875D3D6}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AoC2022.Day1", "AoC2022.Day1\AoC2022.Day1.csproj", "{620896E5-2412-4713-BA7B-ABB66875D3D6}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution