Separate day 1 logic

This commit is contained in:
Alex Thomassen 2022-12-02 16:46:35 +01:00
parent 5af95288a4
commit 8ccd370cf5
Signed by: Alex
GPG Key ID: 10BD786B5F6FF5DE
2 changed files with 64 additions and 52 deletions

39
Handlers/Day01.cs Normal file
View File

@ -0,0 +1,39 @@
namespace AdventOfCode2022.Handlers
{
public class Day01
{
string[] elves;
IEnumerable<int> 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}");
}
}
}

View File

@ -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<int> allCalories = new List<int>();
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();
}
}
}