Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var input = File.ReadAllText("input.txt").Split(',');
- var hashes = input.Select(Hash).ToList();
- Console.WriteLine($"Part 1: {hashes.Sum()}");
- var boxes = new List<List<(string Name, int FocalLength)>>();
- Enumerable.Range(0, 256).ToList().ForEach(_ => boxes.Add(new()));
- var separator = new[] { '=', '-' };
- foreach (var step in input)
- {
- var instructions = step.Split(separator, StringSplitOptions.RemoveEmptyEntries);
- var lensName = instructions[0];
- var box = boxes[Hash(lensName)];
- if (instructions.Length == 2)
- {
- var focalLength = int.Parse(instructions[1]);
- var lens = (lensName, focalLength);
- var lensIndex = box.FindIndex(l => l.Name == lensName);
- if (lensIndex > -1)
- {
- box[lensIndex] = lens;
- }
- else
- {
- box.Add(lens);
- }
- }
- else
- {
- var lens = box.FirstOrDefault(l => l.Name == lensName);
- if (lens != default)
- {
- box.Remove(lens);
- }
- }
- }
- var part2 = 0;
- for (var boxIndex = 0; boxIndex < boxes.Count; boxIndex++)
- {
- part2 += boxes[boxIndex]
- .Select((lens, lensIndex) => lens.FocalLength * (lensIndex + 1) * (boxIndex + 1))
- .Sum();
- }
- Console.WriteLine($"Part 2: {part2}");
- return;
- static int Hash(string s)
- {
- var i = 0;
- foreach (var c in s)
- {
- i += c;
- i *= 17;
- i %= 256;
- }
- return i;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement