-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay15.cs
106 lines (90 loc) · 2.54 KB
/
Day15.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
namespace _2023_cs;
public class Day15
{
private static int hash(string sequence)
{
int hash = 0;
foreach (var c in sequence)
{
hash += c;
hash *= 17;
hash %= 256;
}
return hash;
}
class Lens
{
public string Label { get; set; }
public int FocalLength { get; set; }
public Lens(string label, int focalLength)
{
Label = label;
FocalLength = focalLength;
}
}
private static void removeLens(List<Lens> box, string label)
{
foreach (var t in box)
{
if (t.Label == label)
{
box.Remove(t);
return;
}
}
}
private static void replaceLens(List<Lens> box, string label, int focalLength)
{
foreach (var t in box)
{
if (t.Label == label)
{
t.FocalLength = focalLength;
return;
}
}
box.Add(new Lens(label, focalLength));
}
public static void solve(string filename)
{
int sum1 = 0;
int sum2 = 0;
List<Lens>[] boxes = new List<Lens>[256];
for (int i = 0; i < 256; i++)
{
boxes[i] = new List<Lens>();
}
List<string> lines = Util.ParseFile(filename);
foreach (var line in lines)
{
string[] sequences = line.Split(',');
foreach (var sequence in sequences)
{
sum1 += hash(sequence);
int actionIndex = sequence.IndexOf('=');
if (actionIndex == -1)
{
actionIndex = sequence.IndexOf('-');
}
string label = sequence[..actionIndex];
int boxid = hash(label);
if (sequence[actionIndex] == '=')
{
replaceLens(boxes[boxid], label, sequence[actionIndex+1]-'0');
}
else
{
removeLens(boxes[boxid],label);
}
}
}
for (int i = 0; i < boxes.Length; i++)
{
for (int j = 0; j < boxes[i].Count; j++)
{
sum2 += (i + 1) * (j+1) * boxes[i][j].FocalLength;
}
}
Util.PrintResult(sum1, sum2, 15);
}
}