-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay01.cs
49 lines (40 loc) · 1.4 KB
/
Day01.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
namespace advent_of_code_csharp_2024;
public class Day01
{
public static readonly string InputFilename = @"../../../Day01_input.txt";
public record Line(int First, int Second);
public static Line ParseLine(string line)
{
var split = line.Split(" ", StringSplitOptions.RemoveEmptyEntries);
return new Line(int.Parse(split[0]), int.Parse(split[1]));
}
public static int SolveDay1_Part1(IEnumerable<Line> lines)
{
var leftOrdered = lines.OrderBy(x => x.First);
var rightOrdered = lines.OrderBy(x => x.Second);
return leftOrdered
.Zip(rightOrdered, (a, b) => Math.Abs(a.First - b.Second))
.Sum();
}
public static int SolveDay1_Part2(IEnumerable<Line> parsedLines)
{
var list1 = parsedLines.Select(_ => _.First);
var list2 = parsedLines.Select(_ => _.Second);
var groupedList2 = list2.GroupBy(_ => _).ToList();
var answer =
list1.Select(list1Item =>
{
var x = groupedList2
.FirstOrDefault(x => x.Key == list1Item);
if (x == null)
{
return 0;
}
else
{
return list1Item * x.Count();
}
}).Sum();
return answer;
}
}