Advertisement
mgla

Advent of Code 2023 - Day 11

Dec 11th, 2023 (edited)
663
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.79 KB | None | 0 0
  1. var input = File.ReadAllLines("input.txt");
  2.  
  3. var startingGalaxies = new List<(int Row, int Column)>();
  4. var emptyRows = new List<int>();
  5.  
  6. for (var row = 0; row < input.Length; row++)
  7. {
  8.     var line = input[row];
  9.     if (!line.Contains('#'))
  10.     {
  11.         emptyRows.Add(row);
  12.     }
  13.  
  14.     for (var col = 0; col < line.Length; col++)
  15.     {
  16.         var c = line[col];
  17.         if (c == '#')
  18.         {
  19.             startingGalaxies.Add((row, col));
  20.         }
  21.     }
  22. }
  23.  
  24. var emptyCols = new List<int>();
  25. for (var col = 0; col < input[0].Length; col++)
  26. {
  27.     if (startingGalaxies.All(g => g.Column != col))
  28.     {
  29.         emptyCols.Add(col);
  30.     }
  31. }
  32.  
  33. Console.WriteLine($"Part 1: {CalculateDistances()}");
  34. Console.WriteLine($"Part 2: {CalculateDistances(1_000_000)}");
  35. return;
  36.  
  37. long CalculateDistances(int factor = 2)
  38. {
  39.     var galaxies = new List<(int Row, int Column)>(startingGalaxies);
  40.  
  41.     foreach (var emptyRow in emptyRows)
  42.     {
  43.         for (var i = 0; i < startingGalaxies.Count; i++)
  44.         {
  45.             if (startingGalaxies[i].Row > emptyRow)
  46.             {
  47.                 galaxies[i] = (galaxies[i].Row + factor - 1, galaxies[i].Column);
  48.             }
  49.         }
  50.     }
  51.  
  52.     foreach (var emptyCol in emptyCols)
  53.     {
  54.         for (var i = 0; i < startingGalaxies.Count; i++)
  55.         {
  56.             if (startingGalaxies[i].Column > emptyCol)
  57.             {
  58.                 galaxies[i] = (galaxies[i].Row, galaxies[i].Column + factor - 1);
  59.             }
  60.         }
  61.     }
  62.  
  63.     var result = 0L;
  64.    
  65.     for (var i = 0; i < galaxies.Count - 1; i++)
  66.     {
  67.         for (var j = i + 1; j < galaxies.Count; j++)
  68.         {
  69.             result += Math.Abs(galaxies[j].Row - galaxies[i].Row) + Math.Abs(galaxies[j].Column - galaxies[i].Column);
  70.         }
  71.     }
  72.  
  73.     return result;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement