Equd

AdventOfCode 2018 Day 05

Dec 5th, 2018
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.55 KB | None | 0 0
  1. void Main()
  2. {
  3.     ///TEST PART
  4.     Debug.Assert(GetAnswerA("dabAcCaCBAcCcaDA") == 10);
  5.     Debug.Assert(GetAnswerB("dabAcCaCBAcCcaDA") == 4);
  6.    
  7.     var aoc = new AdventOfCode(2018, 5);   
  8.        
  9.     aoc.SubmitAnswer(GetAnswerA(aoc.InputLines[0]), Part.A);   
  10.     aoc.SubmitAnswer(GetAnswerB(aoc.InputLines[0]), Part.B);   
  11. }
  12.  
  13. public int GetAnswerB(string input)
  14. {
  15.     //keep track of the shortest length found
  16.     int best = int.MaxValue;
  17.    
  18.     //remove each letter in the alphabet
  19.     for (char i = 'a'; i <= 'z'; i++)
  20.     {
  21.         //remove the upper and lower
  22.         var result = input.Replace(i.ToString(), "");
  23.         result = result.Replace(i.ToString().ToUpper(), "");
  24.  
  25.         //get the resulting length
  26.         best = Math.Min(GetAnswerA(result), best);
  27.     }
  28.    
  29.     return best;
  30. }
  31.  
  32. public int GetAnswerA(string result)
  33. {  
  34.     //to array, so we can change values
  35.     var linked = result.ToArray();
  36.  
  37.     //keep track if the lenght changed
  38.     int len = 0;
  39.  
  40.     //keep repeating while the length changes
  41.     while (len != linked.Length)
  42.     {  
  43.         //update length
  44.         len = linked.Length;
  45.        
  46.         //move over the array
  47.         for(int i = 0; i < linked.Length - 1; i++)
  48.         {
  49.             int j = i + 1; 
  50.             //check inside the array?, are the upper and lower diff is 32 in dec)
  51.             while(i >= 0 && j < linked.Length && Math.Abs(linked[i] - linked[j]) == 32)
  52.             {
  53.                 //replate by null
  54.                 linked[i--] = '\0';  //move i back  
  55.                 linked[j++] = '\0'; //move j forward (not on nulls anymore)
  56.             }          
  57.             i = j -1; //continue where we were
  58.         }
  59.        
  60.         //new array
  61.         linked = linked.Where(x => x != '\0').ToArray();       
  62.     }
  63.    
  64.     return linked.Length;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment