-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay01.cs
More file actions
74 lines (57 loc) · 2.03 KB
/
Day01.cs
File metadata and controls
74 lines (57 loc) · 2.03 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using System.Diagnostics;
using _2024.Utils;
namespace _2024._01;
public sealed class Day01 : Base
{
public Day01(bool example) : base(example)
{
Day = "01";
}
private void ParseInput(string[] input, out List<int> firstList, out List<int> secondList)
{
firstList = new List<int>();
secondList = new List<int>();
foreach(string line in input)
{
string[] ids = line.Split(" ");
bool valid = int.TryParse(ids[0], out int first);
valid &= int.TryParse(ids[1], out int second);
if (!valid)
{
throw new Exception($"Invalid input: {line}");
}
firstList.Add(first);
secondList.Add(second);
}
}
public override object PartOne()
{
string[] input = ReadInput();
ParseInput(input, out List<int> firstIdList, out List<int> secondIdList);
Debug.Assert(firstIdList.Count == secondIdList.Count);
int distances = 0;
while (firstIdList.Count > 0)
{
int firstMin = firstIdList.IndexOfMin();
int secondMin = secondIdList.IndexOfMin();
distances += Math.Abs(firstIdList[firstMin] - secondIdList[secondMin]);
firstIdList.RemoveAt(firstMin);
secondIdList.RemoveAt(secondMin);
}
return distances.ToString();
}
public override object PartTwo()
{
string[] input = ReadInput();
ParseInput(input, out List<int> firstIdList, out List<int> secondIdList);
Debug.Assert(firstIdList.Count == secondIdList.Count);
var occurrences = secondIdList.GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count());
int distances = 0;
foreach (int id in firstIdList)
{
distances += id * occurrences.GetValueOrDefault(id, 0);
}
return distances.ToString();
}
}