Advertisement
Equd

AdventOfCode 2018 Day 02

Dec 2nd, 2018
537
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.56 KB | None | 0 0
  1. void Main()
  2. {
  3.     //test if all works
  4.     var testA = new string[] { "abcdef", "bababc", "abbcde", "abcccd", "aabcdd", "abcdee", "ababab", };
  5.     var testB = new string[] { "abcde", "fghij", "klmno", "pqrst", "fguij", "axcye", "wvxyz", };
  6.  
  7.     //verify
  8.     Debug.Assert(GetAnswerA(testA) == 12);
  9.     Debug.Assert(GetAnswerB(testB) == "fgij");
  10.  
  11.  
  12.     //Run
  13.     var aoc = new AdventOfCode(2018, 2);
  14.    
  15.     //part A
  16.     aoc.SubmitAnswer(GetAnswerA(aoc.InputLines), Part.A);
  17.    
  18.     //part B
  19.     aoc.SubmitAnswer(GetAnswerB(aoc.InputLines), Part.B);
  20.    
  21. }
  22.  
  23. public string GetAnswerB(string[] lines)
  24. {
  25.     string best = "";
  26.     for(int i = 0; i < lines.Length; i++)
  27.     {
  28.         for(int j = i +1; j < lines.Length; j++)
  29.         {
  30.             var score = new string(lines[i].Zip(lines[j], (a,b) => (a, b)) //create tuple to chars
  31.                 .Where(x => x.a == x.b) //keep the chars that are identical
  32.                 .Select(x=> x.a).ToArray()); //keep 1 of the 2, and create a string
  33.                
  34.             if(best.Length < score.Length) best = score; //save the longest                        
  35.         }
  36.     }
  37.    
  38.     return best;
  39.    
  40. }
  41.  
  42. public int GetAnswerA(string[] lines)
  43. {
  44.     return lines.SelectMany(
  45.                             row => row.GroupBy(x => x) //for a string group on chars, and mamre readable tuple
  46.                                     .Select(x => x.Count())
  47.                                     .Where(x => x >= 2) //keep bigger than 2                                   
  48.                                     .Distinct() //remove duplicates
  49.                                 )   //we now have for each row, the unique duplicate counts
  50.         .GroupBy(x => x)    //group the counts
  51.         .Select(x => x.Count()) //see how often each is there
  52.         .Aggregate(1, ((x, y) => x * y)) //multiple
  53.         ;
  54. }
  55.  
  56. // Define other methods and classes here
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement