Advertisement
Equd

AOC 2020 Day 13

Dec 13th, 2020
740
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.84 KB | None | 0 0
  1. #load "xunit"
  2. #load "..\AOC Connector"
  3.  
  4. void Main(string[] args)
  5. {
  6.     if(args == null)
  7.         RunTests();  // Call RunTests() or press Alt+Shift+T to initiate testing.
  8.  
  9.     //get aoc data
  10.     var aoc = new AdventOfCode(2020, 13);
  11.    
  12.     //solve A
  13.     aoc.SubmitAnswer(SolveA(aoc.InputLines), Part.A);
  14.  
  15.     //solve B
  16.     aoc.SubmitAnswer(SolveB(aoc.InputLines), Part.B);
  17. }
  18.  
  19.  
  20.  
  21. int SolveA(string[] data)
  22. {
  23.     int time = int.Parse(data[0]);
  24.     var firstBus = data[1].Split(',')
  25.         .Where(x => x != "x") //split remove empty
  26.         .Select(x => int.Parse(x)) //get ints
  27.         .Select(x => (bus: x, minTillNext: x - (time % x)))    
  28.         .OrderBy(x => x.minTillNext)       
  29.         .First();
  30.        
  31.    
  32.        
  33.     return firstBus.minTillNext * firstBus.bus;
  34. }
  35. ulong SolveB(string[] data)
  36. {
  37.     //create a list with the busses and theid offsets
  38.     var buses = data[1].Split(',')
  39.         .Select((x, i) => (x, i))
  40.         .Where(x => x.x != "x")
  41.         .Select(item => new { bus = ulong.Parse(item.x), offset = (ulong) item.i})             
  42.         .ToList();
  43.  
  44.     //list with the available busses
  45.     var allBuses = buses.ToList();
  46.  
  47.     //track the time and stepsize
  48.     ulong time = 0;    
  49.     ulong stepSize = 1;
  50.    
  51.     //loop through th e
  52.     while (buses.Count > 0)
  53.     {      
  54.         //increment the time with the stepsize
  55.         time += stepSize;
  56.        
  57.         //is this the point where the busses are in sync                               
  58.         if((time + buses[0].offset) % buses[0].bus == 0)
  59.         {
  60.             //multiple the stepsize with the current step          
  61.             stepSize *= buses[0].bus;
  62.             //remove this bus
  63.             buses.RemoveAt(0);             
  64.         }
  65.                        
  66.     }
  67.    
  68.     //done
  69.     return time;   
  70. }
  71.  
  72.  
  73. // You can define other methods, fields, classes and namespaces here
  74.  
  75. #region private::Tests
  76. //test data
  77. string[] testdata = new[]
  78. {
  79. "939",
  80. "7,13,x,x,59,x,31,19"
  81. };
  82.  
  83. //tests
  84. [Fact] void TestA() => Assert.Equal(295, SolveA(testdata));
  85. [Fact] void TestB() => Assert.Equal((ulong)1068781, SolveB(testdata));
  86.  
  87. #endregion
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement