-
Notifications
You must be signed in to change notification settings - Fork 1
/
Program.cs
56 lines (47 loc) · 1.34 KB
/
Program.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
using AdventOfCode.Common;
var instructions = Resources.GetInputFileLines()
.Single()
.SplitBy(",");
var boxes = Enumerable.Range(0, 256)
.Select(_ => new LinkedList<Lens>())
.ToArray();
foreach (var instruction in instructions)
{
var index1 = instruction.IndexOf('=');
var index2 = instruction.IndexOf('-');
var label = instruction[0..Math.Max(index1, index2)];
var box = boxes[Hash(label)];
var lens = box.FirstOrDefault(lens => lens.Label == label);
if (index1 != -1) // =
{
var length = int.Parse(instruction.Substring(index1 + 1));
if (lens != null)
{
lens.FocalLength = length;
}
else
{
box.AddLast(new Lens(label, length));
}
}
else if (lens != null) // -
{
box.Remove(lens);
}
}
var part1 = instructions
.Select(Hash)
.Sum();
var part2 = boxes
.SelectMany((box, boxId) =>
box.Select((lens, lensId) => (1 + boxId) * (lensId + 1) * lens.FocalLength))
.Sum();
Console.WriteLine($"Part 1: {part1}");
Console.WriteLine($"Part 2: {part2}");
static int Hash(string input)
=> input.Aggregate(0, (acc, c) => acc = (acc + c) * 17 % 256);
file class Lens(string label, int focalLength)
{
public string Label { get; } = label;
public int FocalLength { get; set; } = focalLength;
}