70 lines
2.1 KiB
C#
70 lines
2.1 KiB
C#
namespace Day1;
|
|
|
|
// Advent of Code 2024
|
|
// Day 1
|
|
// James Plante (jwplante)
|
|
|
|
class DayOne
|
|
{
|
|
private static async Task PartOne()
|
|
{
|
|
await using FileStream inputStream = File.OpenRead("input/day1.txt");
|
|
PairParser parser = new();
|
|
|
|
IList<(int, int)> entries = await parser.ParseAsync(inputStream);
|
|
|
|
// Given the parsed entries, add them to two new lists and sort them
|
|
List<int> leftList = [];
|
|
List<int> rightList = [];
|
|
foreach ((int left, int right) in entries)
|
|
{
|
|
leftList.Add(left);
|
|
rightList.Add(right);
|
|
}
|
|
leftList.Sort();
|
|
rightList.Sort();
|
|
|
|
// Convert back into pairs of (smallest, smallest), (secondSmallest, ...
|
|
List<(int, int)> sortedPairs = leftList
|
|
.Zip(rightList, (left, right) => (left, right))
|
|
.ToList();
|
|
|
|
long totalDistance = 0;
|
|
foreach ((int left, int right) in sortedPairs)
|
|
{
|
|
var lineDistance = Math.Abs(left - right);
|
|
totalDistance += lineDistance;
|
|
}
|
|
|
|
Console.WriteLine($"Part 1: The total distance of the lines is {totalDistance}.");
|
|
}
|
|
|
|
private static async Task PartTwo()
|
|
{
|
|
await using FileStream inputStream = File.OpenRead("input/day1.txt");
|
|
PairParser parser = new();
|
|
|
|
IList<(int, int)> entries = await parser.ParseAsync(inputStream);
|
|
|
|
// Get the frequencies for the right list
|
|
Dictionary<int, int> frequencies = [];
|
|
foreach ((_, int right) in entries)
|
|
{
|
|
frequencies[right] = frequencies.GetValueOrDefault(right) + 1;
|
|
}
|
|
|
|
long similarityScore = 0;
|
|
foreach ((int left, _) in entries)
|
|
{
|
|
var intermediateScore = left * frequencies.GetValueOrDefault(left);
|
|
similarityScore += intermediateScore;
|
|
}
|
|
Console.WriteLine($"Part 2: The total similarity score is {similarityScore}.");
|
|
}
|
|
|
|
public static async Task Main(string[] args)
|
|
{
|
|
await PartOne();
|
|
await PartTwo();
|
|
}
|
|
} |