Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #load "xunit"
- #load "..\AOC Connector"
- void Main(string[] args)
- {
- if(args == null)
- RunTests(); // Call RunTests() or press Alt+Shift+T to initiate testing.
- //get aoc data
- var aoc = new AdventOfCode(2020, 13);
- //solve A
- aoc.SubmitAnswer(SolveA(aoc.InputLines), Part.A);
- //solve B
- aoc.SubmitAnswer(SolveB(aoc.InputLines), Part.B);
- }
- int SolveA(string[] data)
- {
- int time = int.Parse(data[0]);
- var firstBus = data[1].Split(',')
- .Where(x => x != "x") //split remove empty
- .Select(x => int.Parse(x)) //get ints
- .Select(x => (bus: x, minTillNext: x - (time % x)))
- .OrderBy(x => x.minTillNext)
- .First();
- return firstBus.minTillNext * firstBus.bus;
- }
- ulong SolveB(string[] data)
- {
- //create a list with the busses and theid offsets
- var buses = data[1].Split(',')
- .Select((x, i) => (x, i))
- .Where(x => x.x != "x")
- .Select(item => new { bus = ulong.Parse(item.x), offset = (ulong) item.i})
- .ToList();
- //list with the available busses
- var allBuses = buses.ToList();
- //track the time and stepsize
- ulong time = 0;
- ulong stepSize = 1;
- //loop through th e
- while (buses.Count > 0)
- {
- //increment the time with the stepsize
- time += stepSize;
- //is this the point where the busses are in sync
- if((time + buses[0].offset) % buses[0].bus == 0)
- {
- //multiple the stepsize with the current step
- stepSize *= buses[0].bus;
- //remove this bus
- buses.RemoveAt(0);
- }
- }
- //done
- return time;
- }
- // You can define other methods, fields, classes and namespaces here
- #region private::Tests
- //test data
- string[] testdata = new[]
- {
- "939",
- "7,13,x,x,59,x,31,19"
- };
- //tests
- [Fact] void TestA() => Assert.Equal(295, SolveA(testdata));
- [Fact] void TestB() => Assert.Equal((ulong)1068781, SolveB(testdata));
- #endregion
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement