Equd

AoC 2021 Day 07

Dec 7th, 2021 (edited)
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.79 KB | None | 0 0
  1. #load "xunit"
  2. #load ".\AoCConnector"
  3. #load ".\2dArrayExtensions"
  4.  
  5. async Task Main()
  6. {
  7.    
  8.     RunTests();  // Call RunTests() or press Alt+Shift+T to initiate testing.
  9.  
  10.     var aoc = AoC.GetAOC(2021, 7);     
  11.        
  12.     var answerA = SolveA(aoc.GetLines);
  13.     await aoc.SubmitAnswer(Part.Part1, answerA);   
  14.    
  15.    
  16.     var answerB = SolveB(aoc.GetLines);
  17.     await aoc.SubmitAnswer(Part.Part2, answerB.ToString().Dump()); 
  18. }
  19.  
  20. public int SolveA(string[] lines) => Solve(lines, true);
  21. public int SolveB(string[] lines) => Solve(lines, false);
  22.  
  23. public int Solve(string[] lines, bool v1)
  24. {
  25.     //parse the data
  26.     var inputArray = lines[0].Split(',').Select(x => int.Parse(x)).ToArray();
  27.     Dictionary<int, int> dicCache = new Dictionary<int, int>();
  28.  
  29.     int min = 0;
  30.     int max = inputArray.Length - 1;
  31.     while (min <= max)
  32.     {
  33.         int mid = (min + max) / 2;
  34.         int midLeft = mid - ((mid - min) / 2);
  35.         int midRight = mid + ((max - mid) / 2);
  36.  
  37.         int leftValue = GetValue(midLeft);
  38.         int rightValue = GetValue(midRight);
  39.  
  40.         if (rightValue < leftValue)
  41.         {
  42.             min = midLeft;
  43.         }
  44.         else if (leftValue < rightValue)
  45.         {
  46.             max = midRight;
  47.         }
  48.         else
  49.         {
  50.             return GetValue(mid);
  51.         }
  52.     }
  53.     throw new NotImplementedException();
  54.  
  55.     int GetValue(int target)
  56.     {
  57.         if (dicCache.TryGetValue(target, out var result) == false)
  58.         {
  59.             result = 0;
  60.             for (int f = 0; f < inputArray.Length; f++)
  61.             {
  62.                 var dist = Math.Abs(target - inputArray[f]);
  63.                
  64.                 if(v1)
  65.                     result += dist;
  66.                 else
  67.                     result += dist * (dist + 1) / 2;
  68.             }
  69.             dicCache[target] = result;
  70.         }
  71.         return result;
  72.     }
  73. }
  74.  
  75.  
  76. #region private::Tests
  77.  
  78. string[] TestData = new []
  79. {
  80. "16,1,2,0,4,2,7,1,2,14"
  81. };
  82.  
  83. [Fact] void Test_SolvaA() => Assert.Equal(37, SolveA(TestData));
  84. [Fact] void Test_SolveB() => Assert.Equal(168, SolveB(TestData));
  85.  
  86. #endregion
Advertisement
Add Comment
Please, Sign In to add comment