Advertisement
mgla

Advent of Code 2023 - Day 18

Dec 18th, 2023 (edited)
812
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.14 KB | None | 0 0
  1. var input = File.ReadAllLines("input.txt");
  2.  
  3. var polygon1 = new List<(long Row, long Col)>();
  4. (long Row, long Col) currentPosition1 = (0, 0);
  5. var circumference1 = 0.0;
  6.  
  7. var polygon2 = new List<(long Row, long Col)>();
  8. (long Row, long Col) currentPosition2 = (0, 0);
  9. var circumference2 = 0.0;
  10.  
  11. foreach (var line in input)
  12. {
  13.     polygon1.Add(currentPosition1);
  14.     var move = line.Split(' ');
  15.  
  16.     var length1 = int.Parse(move[1]);
  17.     currentPosition1 = move[0] switch
  18.     {
  19.         "R" => (currentPosition1.Row, currentPosition1.Col + length1),
  20.         "D" => (currentPosition1.Row + length1, currentPosition1.Col),
  21.         "L" => (currentPosition1.Row, currentPosition1.Col - length1),
  22.         "U" => (currentPosition1.Row - length1, currentPosition1.Col),
  23.         _ => throw new Exception("Unknown direction")
  24.     };
  25.  
  26.     circumference1 += length1;
  27.  
  28.     polygon2.Add(currentPosition2);
  29.     var hex = move[2].TrimStart('(').TrimEnd(')');
  30.     var length2 = long.Parse(hex[1..^1], System.Globalization.NumberStyles.HexNumber);
  31.  
  32.     currentPosition2 = hex.Last() switch
  33.     {
  34.         '0' => (currentPosition2.Row, currentPosition2.Col + length2), // R
  35.         '1' => (currentPosition2.Row + length2, currentPosition2.Col), // D
  36.         '2' => (currentPosition2.Row, currentPosition2.Col - length2), // L
  37.         '3' => (currentPosition2.Row - length2, currentPosition2.Col), // U
  38.         _ => throw new Exception("Unknown direction")
  39.     };
  40.  
  41.     circumference2 += length2;
  42. }
  43.  
  44. Console.WriteLine($"Part 1: {Area(polygon1) + circumference1 / 2 + 1}");
  45. Console.WriteLine($"Part 2: {Area(polygon2) + circumference2 / 2 + 1}");
  46. return;
  47.  
  48. // Shoelace formula, found it on the internet:
  49. // https://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area#C#
  50. static double Area(List<(long Row, long Col)> polygon)
  51. {
  52.     var n = polygon.Count;
  53.     var result = 0.0;
  54.     for (var i = 0; i < n - 1; i++)
  55.     {
  56.         result += polygon[i].Row * polygon[i + 1].Col - polygon[i + 1].Row * polygon[i].Col;
  57.     }
  58.  
  59.     result = Math.Abs(result + polygon[n - 1].Row * polygon[0].Col - polygon[0].Row * polygon[n - 1].Col) / 2.0;
  60.     return result;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement