Skip to content

Commit afbde3f

Browse files
authored
Merge pull request #1 from shadeon/day1
Day 1 - Calorie Counting
2 parents 2465e3f + 012f661 commit afbde3f

File tree

8 files changed

+2403
-0
lines changed

8 files changed

+2403
-0
lines changed

2022/C#/day1/code/Day1.cs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
public class Day1
2+
{
3+
private readonly IEnumerable<string> _input = File.ReadLines(@".\data\input.txt");
4+
private readonly IEnumerable<string> _sample = File.ReadLines(@".\data\sample.txt");
5+
6+
public int GetPart1Answer() => part1(_input);
7+
8+
public int GetPart1Sample() => part1(_sample);
9+
10+
private int part1(IEnumerable<string> input) =>
11+
getElves(input)
12+
.Max();
13+
14+
public int GetPart2Sample() => part2(_sample);
15+
16+
public int GetPart2Answer() => part2(_input);
17+
18+
private int part2(IEnumerable<string> input) =>
19+
getElves(input)
20+
.OrderByDescending(elf => elf)
21+
.Take(3)
22+
.Sum();
23+
24+
private IEnumerable<int> getElves(IEnumerable<string> input) => input
25+
.Aggregate(newStack<List<int>>(), (acc, line) => {
26+
if (int.TryParse(line, out var foodItem)) {
27+
acc.Peek().Add(foodItem);
28+
}
29+
else {
30+
acc.Push(new List<int>());
31+
}
32+
return acc;
33+
})
34+
.Select(elf => elf.Sum());
35+
36+
private Stack<T> newStack<T>() where T : new() =>
37+
new Stack<T>(new [] {new T()});
38+
}

2022/C#/day1/code/Day1.csproj

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net6.0</TargetFramework>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
<Nullable>enable</Nullable>
8+
</PropertyGroup>
9+
10+
<ItemGroup>
11+
<None Include="..\data\**\*.*" LinkBase="data\" CopyToOutputDirectory="Always" CopyToPublishDirectory="Always"/>
12+
</ItemGroup>
13+
14+
</Project>

2022/C#/day1/code/Program.cs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
var day1 = new Day1();
2+
3+
// Part 1
4+
Console.WriteLine($"Part 1 Answer: {day1.GetPart1Answer()}");
5+
6+
// Part 2
7+
Console.WriteLine($"Part 2 Answer: {day1.GetPart2Answer()}");

0 commit comments

Comments
 (0)