AdventOfCode/AdventOfCode.Solutions/2024/Day 01/Day01.cs
2024-12-01 10:17:24 +01:00

69 lines
1.9 KiB
C#

using AdventOfCode.Core.Shared.IO;
namespace AdventOfCode.Solutions._2024
{
public class Day01 : IChallange
{
public int Year => 2024;
public int Day => 1;
private readonly IInputReader _inputReader;
public Day01(IInputReader inputReader)
{
_inputReader = inputReader;
_inputReader.SetInput(this);
}
//11
//1889772
public async Task<string> GetSolutionPart1()
{
int total = 0;
(List<int> One, List<int> Two) = await GetLists();
One = [.. One.Order()];
Two = [.. Two.Order()];
for (int index = 0; index < One.Count; index++) {
int distance = Math.Abs(One[index] - Two[index]);
total += distance;
}
return total.ToString();
}
//31
//23228917
public async Task<string> GetSolutionPart2()
{
int total = 0;
(List<int> One, List<int> Two) = await GetLists();
var oneGroup = One.GroupBy(x => x);
var twoGroup = Two.GroupBy(x => x);
foreach(var group in oneGroup)
{
var grouptwo = twoGroup.FirstOrDefault(g => g.Key == group.Key)?.Count() ?? 0;
total += group.Key * group.Count() * grouptwo;
}
return total.ToString();
}
private async Task<(List<int> One, List<int> Two)> GetLists()
{
string[] data = await _inputReader.ReadAsArrayString();
List<int> one = [], two = [];
foreach (string s in data)
{
int[] numbers = s.Split(" ").Select(int.Parse).ToArray();
one.Add(numbers[0]);
two.Add(numbers[1]);
}
return (one, two);
}
}
}