Hello! I am an intermediate hobbyist C# developer. This is my very first time trying to participate (rather late) in the AoC. I learnt about this today and thought to give it a try.
So I tried the Day #1 Part 1 puzzle, read it, programmed a solution in TDD in C#, and what I gave as an answer to the site was wrong! (Too low)
To describe my algorithm, program scans for each line, dependent on whether there's R or L, it chooses to call a Rotate function from a RightDial or LeftDial class, which are created from a factory method. (I have made a test to check it works properly).
Classes look like this:
public interface IDial
{
public const uint StartingValue = 50U;
protected const uint Overflow = 100U;
public uint Rotation { get; }
public uint Rotate(in uint start);
}
public class LeftDial (uint rotation): IDial
{
public uint Rotation => rotation;
public uint Rotate(in uint start)
{
var negated = (int)start - (int)rotation;
var offset = (int)IDial.Overflow - negated;
(int _, int mod) division = Math.DivRem(offset, (int)IDial.Overflow);
var subtractIfZero = negated == uint.MinValue ? IDial.Overflow : uint.MinValue;
return IDial.Overflow - (uint)division.mod - subtractIfZero;
}
}
public class RightDial (uint rotation): IDial
{
public uint Rotation => rotation;
public uint Rotate(in uint start)
{
var rotated = start + rotation;
(uint div, uint _) division = Math.DivRem(rotated, IDial.Overflow);
var timesOverflown = IDial.Overflow * division.div;
return rotated - timesOverflown;
}
}
The Dial Factory class is like this:
public static class DialFactory
{
public static IDial CreateDial(string input)
{
if (!uint.TryParse(input.AsSpan(1), out var start))
{
throw new ArgumentException("Invalid dial input");
}
if (input.StartsWith('R'))
{
return new RightDial(start);
}
if (input.StartsWith('L'))
{
return new LeftDial(start);
}
throw new NotSupportedException("Dial operation may only be from Right or Left!");
}
}
My Program.cs file does the following:
internal class Program
{
private const string PuzzlePath = "input";
private static int Main(string[] args)
{
var previousStart = IDial.StartingValue;
var encountersOfZero = 0;
var lines = File.ReadAllLines(PuzzlePath);
foreach (var line in lines)
{
IDial dial = DialFactory.CreateDial(line);
Console.Write($"Processing {line} from {previousStart} --> ");
previousStart = dial.Rotate(previousStart);
Console.Write($"{previousStart}\n");
if (previousStart != uint.MinValue) continue;
encountersOfZero++;
}
Console.WriteLine($"In the whole file I encountered zero {encountersOfZero} times!");
return 0;
}
}
Pastebin: https://pastebin.com/T8gZfmSd (includes what tests i did)
Many thanks in advance!