feat: start solving part 2

This commit is contained in:
Stevan Freeborn
2023-12-22 22:23:57 -06:00
parent 6a74157ed3
commit 089ebe96af
+86 -22
View File
@@ -19,35 +19,99 @@ public class Program
} }
var input = await File.ReadAllTextAsync(args[0]); var input = await File.ReadAllTextAsync(args[0]);
var steps = input.Split(
',',
StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries
);
var stopwatch = new Stopwatch(); var stopwatch = new Stopwatch();
stopwatch.Start(); stopwatch.Start();
var total = 0; var result = LaunchSequence
.Parse(input)
foreach (var step in steps) .Steps
{ .Sum(step => step.HashLabel());
var stepValue = 0;
foreach (var character in step)
{
var ascii = (int)character;
stepValue += ascii;
stepValue *= 17;
stepValue %= 256;
}
total += stepValue;
}
stopwatch.Stop(); stopwatch.Stop();
Console.WriteLine($"The total is {total}. ({stopwatch.ElapsedMilliseconds}ms)"); Console.WriteLine($"The total is {result}. ({stopwatch.ElapsedMilliseconds}ms)");
return total; return result;
} }
} }
public class LaunchSequence(
List<Step> steps
)
{
public List<Step> Steps { get; init; } = steps;
public long Initialize()
{
var boxes = new Dictionary<int, Dictionary<string, int>>();
foreach (var num in Enumerable.Range(0, 255))
{
boxes.Add(num, []);
}
return 0;
}
public static LaunchSequence Parse(string input, bool part2 = false)
{
var steps = input
.Split(
',',
StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries
)
.Select(step => Step.Parse(step, part2))
.ToList();
return new LaunchSequence(steps);
}
}
public class Step(
string label,
Operation operation,
int? lensFocalLength
)
{
public string Label { get; init; } = label;
public Operation Operation { get; init; } = operation;
public int? LensFocalLength { get; init; } = lensFocalLength;
public int HashLabel() => Label
.Aggregate(0, (hash, character) =>
{
var ascii = (int)character;
hash += ascii;
hash *= 17;
hash %= 256;
return hash;
});
public static Step Parse(string input, bool part2 = false)
{
if (input.Contains('-'))
{
var label = part2 ? input.Trim('-') : input;
return new Step(label, Operation.Removal, null);
}
if (input.Contains('='))
{
var parts = input.Split('=');
var label = part2 ? parts[0] : parts[0] + "=" + parts[1];
var focalLength = int.Parse(parts[1]);
return new Step(label, Operation.Insertion, focalLength);
}
throw new ArgumentException("Invalid input.", nameof(input));
}
}
public enum Operation
{
Removal,
Insertion,
}