-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday1.cs
66 lines (57 loc) · 1.87 KB
/
day1.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// [Day 1: Historian Hysteria](https://adventofcode.com/2024/day/1)
using System;
using System.Collections.Generic;
using System.IO;
class day1
{
static void Main(string[] args)
{
// Default to "input.txt" if no argument is provided
string inputFile = args.Length == 0 ? "input.txt" : args[0];
// Lists to store the values
List<int> left = new List<int>();
List<int> right = new List<int>();
// Read the file and populate the left and right lists
foreach (var line in File.ReadLines(inputFile))
{
// Split the line by any whitespace (spaces or tabs)
var parts = line.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
// Add the two integers to left and right lists
left.Add(int.Parse(parts[0]));
right.Add(int.Parse(parts[1]));
}
// Sort both lists
left.Sort();
right.Sort();
// Part 1: Calculate the sum of absolute differences
int part1Result = 0;
for (int i = 0; i < left.Count; i++)
{
part1Result += Math.Abs(left[i] - right[i]);
}
Console.WriteLine(part1Result);
// Part 2: Count occurrences of each element in the right list
Dictionary<int, int> rightCounts = new Dictionary<int, int>();
foreach (var num in right)
{
if (rightCounts.ContainsKey(num))
{
rightCounts[num]++;
}
else
{
rightCounts[num] = 1;
}
}
// Calculate the weighted sum for part 2
int part2Result = 0;
foreach (var num in left)
{
if (rightCounts.ContainsKey(num))
{
part2Result += num * rightCounts[num];
}
}
Console.WriteLine(part2Result);
}
}