Advent of Code 2022

Es gibt 85 Antworten in diesem Thema. Der letzte Beitrag () ist von Elanda.

    Day 12:

    Spoiler anzeigen

    C#-Quellcode

    1. [b]
    2. [/b]namespace Twelve;
    3. using System.Diagnostics;
    4. using System.Numerics;
    5. public class Program
    6. {
    7. static Grid _grid = null;
    8. static void Main(string[] args)
    9. {
    10. IEnumerable<string> data = File.ReadAllLines("input.txt");
    11. _grid = new Grid(data);
    12. Log(_grid.FindAPathAtAll(1));
    13. Log(_grid.FindAPathAtAll(2));
    14. }
    15. static void Log(object message) => Console.WriteLine(message);
    16. }
    17. class Node
    18. {
    19. public int X { get; set; }
    20. public int Y { get; set; }
    21. public char Value { get; set; }
    22. public int Distance { get; set; }
    23. public int NextDistance { get; set; }
    24. public Node(int x, int y, char value) => (x, y, value) = (this.X = x, this.Y = y, this.Value = value);
    25. }
    26. class Grid
    27. {
    28. public Node[,] Nodes { get; set; }
    29. private Node _startNode = null;
    30. private Node _endNode = null;
    31. public Grid(IEnumerable<string> data)
    32. {
    33. this.Nodes = new Node[data.ElementAt(0).Count(), data.Count()];
    34. for (int y = 0; y < data.Count(); y++)
    35. for (int x = 0; x < data.ElementAt(0).Count(); x++)
    36. {
    37. this.Nodes[x, y] = new Node(x, y, data.ElementAt(y).ElementAt(x));
    38. if (data.ElementAt(y).ElementAt(x) == 'S')
    39. {
    40. _startNode = this.Nodes[x, y];
    41. this.Nodes[x, y].Value = 'a';
    42. }
    43. if (data.ElementAt(y).ElementAt(x) == 'E')
    44. {
    45. _endNode = this.Nodes[x, y];
    46. this.Nodes[x, y].Value = 'z';
    47. }
    48. this.Nodes[x, y].Distance = 0;
    49. }
    50. }
    51. //"Wave-propagation algo
    52. public int FindAPathAtAll(int part)
    53. {
    54. List<Node> workingNodes = new();
    55. _endNode.NextDistance = 1;
    56. workingNodes.Add(_endNode);
    57. while (true)
    58. {
    59. List<Node> newNodes = new();
    60. foreach (var node in workingNodes)
    61. {
    62. node.Distance = node.NextDistance;
    63. var neighbours = GetNeighbours(node);
    64. foreach (var neighbour in neighbours)
    65. {
    66. if (neighbour.Distance != 0) continue;
    67. if (node.Value - neighbour.Value < 2)
    68. {
    69. neighbour.NextDistance = node.Distance + 1;
    70. newNodes.Add(neighbour);
    71. }
    72. }
    73. }
    74. if (newNodes.Count == 0) break;
    75. workingNodes.Clear();
    76. workingNodes.AddRange(newNodes.Distinct().ToList());
    77. }
    78. if (part == 1) return _startNode.Distance - 1;
    79. if (part == 2)
    80. {
    81. int min = int.MaxValue;
    82. foreach (var node in this.Nodes)
    83. {
    84. if (node.Value == 'a' && node.Distance != 0 && node.Distance < min)
    85. min = node.Distance - 1;
    86. }
    87. return min;
    88. }
    89. return 0;
    90. }
    91. public List<Node> GetNeighbours(Node node)
    92. {
    93. List<Node> result = new();
    94. if (IsOnGrid(node.X - 1, node.Y))
    95. result.Add(this.Nodes[node.X - 1, node.Y]);
    96. if (IsOnGrid(node.X + 1, node.Y))
    97. result.Add(this.Nodes[node.X + 1, node.Y]);
    98. if (IsOnGrid(node.X, node.Y - 1))
    99. result.Add(this.Nodes[node.X, node.Y - 1]);
    100. if (IsOnGrid(node.X, node.Y + 1))
    101. result.Add(this.Nodes[node.X, node.Y + 1]);
    102. return result;
    103. }
    104. public Node GetNode(int x, int y)
    105. {
    106. if (IsOnGrid(x, y))
    107. return this.Nodes[x, y];
    108. return null;
    109. }
    110. public bool IsOnGrid(int x, int y)
    111. {
    112. return (x >= 0 && x < this.Nodes.GetLength(0) &&
    113. y >= 0 && y < this.Nodes.GetLength(1));
    114. }
    115. public bool IsOnGrid(Node node) => IsOnGrid(node.X, node.Y);
    116. }


    Die Unendlichkeit ist weit. Vor allem gegen Ende. ?(
    Manche Menschen sind gar nicht dumm. Sie haben nur Pech beim Denken. 8o
    Tag 12
    Spoiler anzeigen

    finally - der hat mich echt aufgehalten... Der Code ist super schlecht aber funktioniert. Berechnen von Part 2 dauert gefühlt ewig.kann man sicher noch besser machen.... saß da nun gestern und heute paar stunden dran und ja aber endlich mal selbst implementiert das zeug für den Tag und keine fertige lib benutzt das war mir wichtig. danke an @SpaceyX der mir gestern abend noch nen kleinen Tipp gegeben hat sonst wär ich sicher nicht drauf gekommen.
    Gerne per PN oder so noch Vorschläge warum das ganze so lange dauert wo ich etwas verbessern könnte.

    C#-Quellcode

    1. using System.Drawing;
    2. string[] lines = File.ReadAllLines("Input.txt");
    3. Map map2 = new Map(lines);
    4. map2.Initilize();
    5. map2.CalculateNeighbours();
    6. map2.getShortestPathFromStartingNode(map2.Nodes.FirstOrDefault(x => x.IsStart == true));
    7. List<long> shortestPaths = new List<long>();
    8. long shortestPathCost = 0;
    9. shortestPathCost = 0;
    10. List<Knoten> kleinsterweg = new List<Knoten>();
    11. kleinsterweg.Add(map2.Nodes.FirstOrDefault(x => x.IsEnd));
    12. getShortestPath(kleinsterweg, map2.Nodes.FirstOrDefault(x => x.IsEnd));
    13. Console.WriteLine($"Part 1: {kleinsterweg.Count() - 1}");
    14. Console.WriteLine($"checking {map2.Nodes.Where(x => x.Letter == 'a').Count()} Nodes for Part 2");
    15. int counter = 0;
    16. Parallel.ForEach(map2.Nodes.Where(x => x.Letter == 'a' && x.HasValidNeighbours == true), k =>
    17. {
    18. Map map = new Map(lines);
    19. map.Initilize();
    20. map.CalculateNeighbours();
    21. if (!map.getShortestPathFromStartingNode(map.Nodes.FirstOrDefault(x=>x.ID == k.ID))) return;
    22. shortestPathCost = 0;
    23. List<Knoten> kleinsterweg = new List<Knoten>();
    24. kleinsterweg.Add(map.Nodes.FirstOrDefault(x => x.IsEnd));
    25. getShortestPath(kleinsterweg, map.Nodes.FirstOrDefault(x => x.IsEnd));
    26. shortestPaths.Add(kleinsterweg.Count());
    27. });
    28. Console.WriteLine($"Part 2: {shortestPaths.Min()}");
    29. void getShortestPath(List<Knoten> tkn, Knoten node)
    30. {
    31. if (node.LastKnoten == null) return;
    32. tkn.Add(node.LastKnoten);
    33. shortestPathCost += node.Verbindungen.FirstOrDefault(x => x.ConnectedKnoten.ID == node.LastKnoten.ID).Cost;
    34. getShortestPath(tkn, node.LastKnoten);
    35. }
    36. Console.WriteLine("fertig");
    37. public class Map
    38. {
    39. public List<Knoten> Nodes { get; set; } = new List<Knoten>();
    40. public int Rows { get; set; }
    41. public int Cols { get; set; }
    42. public string[] Grid { get; private set; }
    43. public Map(string[] lines)
    44. {
    45. Rows = lines.Count();
    46. Cols = lines[0].Length;
    47. Grid = lines;
    48. }
    49. public void Initilize()
    50. {
    51. int knotenId = 0;
    52. for (int i = 0; i < Rows; i++)
    53. {
    54. for (int x = 0; x < Cols; x++)
    55. {
    56. Knoten k = new Knoten();
    57. int actual = Grid[i][x];
    58. k.Letter = (char)actual;
    59. if ((char)actual == 'S')
    60. {
    61. k.Letter = 'a';
    62. k.IsStart = true;
    63. k.Cost = 0;
    64. }
    65. if ((char)actual == 'E')
    66. {
    67. k.Letter = 'z';
    68. k.IsEnd = true;
    69. }
    70. k.ID = knotenId;
    71. k.Coordinates = new Point(i, x);
    72. knotenId++;
    73. Nodes.Add(k);
    74. }
    75. }
    76. }
    77. public void CalculateNeighbours()
    78. {
    79. foreach (Knoten k in Nodes)
    80. {
    81. Knoten kUp = Nodes.FirstOrDefault(x => x.Coordinates.X == k.Coordinates.X - 1 && x.Coordinates.Y == k.Coordinates.Y);
    82. Knoten kDown = Nodes.FirstOrDefault(x => x.Coordinates.X == k.Coordinates.X + 1 && x.Coordinates.Y == k.Coordinates.Y);
    83. Knoten kLeft = Nodes.FirstOrDefault(x => x.Coordinates.X == k.Coordinates.X && x.Coordinates.Y == k.Coordinates.Y - 1);
    84. Knoten kRight = Nodes.FirstOrDefault(x => x.Coordinates.X == k.Coordinates.X && x.Coordinates.Y == k.Coordinates.Y + 1);
    85. int result = 0;
    86. if (kUp != null)
    87. {
    88. result = ((k.Letter + 1) >= kUp.Letter) ? 1 : 9999;
    89. if (result < 9999) k.HasValidNeighbours = true;
    90. Verbindung v = new Verbindung();
    91. v.Cost = result;
    92. v.ConnectedKnoten = kUp;
    93. k.Verbindungen.Add(v);
    94. }
    95. if (kDown != null)
    96. {
    97. result = ((k.Letter + 1) >= kDown.Letter) ? 1 : 9999;
    98. if (result < 9999) k.HasValidNeighbours = true;
    99. Verbindung v = new Verbindung();
    100. v.Cost = result;
    101. v.ConnectedKnoten = kDown;
    102. k.Verbindungen.Add(v);
    103. }
    104. if (kLeft != null)
    105. {
    106. result = ((k.Letter + 1) >= kLeft.Letter) ? 1 : 9999;
    107. if (result < 9999) k.HasValidNeighbours = true;
    108. Verbindung v = new Verbindung();
    109. v.Cost = result;
    110. v.ConnectedKnoten = kLeft;
    111. k.Verbindungen.Add(v);
    112. }
    113. if (kRight != null)
    114. {
    115. result = ((k.Letter + 1) >= kRight.Letter) ? 1 : 9999;
    116. if (result < 9999) k.HasValidNeighbours = true;
    117. Verbindung v = new Verbindung();
    118. v.Cost = result;
    119. v.ConnectedKnoten = kRight;
    120. k.Verbindungen.Add(v);
    121. }
    122. }
    123. }
    124. public bool getShortestPathFromStartingNode(Knoten start)
    125. {
    126. List<Knoten> queue = new List<Knoten>();
    127. queue.Add(start);
    128. while (queue.Any())
    129. {
    130. Knoten current = queue.OrderBy(x => x.Cost).ToList().First();
    131. queue.Remove(current);
    132. foreach (Verbindung currentConnection in current.Verbindungen.OrderBy(x => x.Cost))
    133. {
    134. Knoten currentChild = currentConnection.ConnectedKnoten;
    135. if (currentChild.Visited) continue;
    136. if (currentChild.Letter > current.Letter + 1) continue;
    137. if (currentChild.Cost == null || current.Cost + currentConnection.Cost < currentChild.Cost)
    138. {
    139. currentChild.Cost = current.Cost + currentConnection.Cost;
    140. currentChild.LastID = current.ID;
    141. currentChild.LastKnoten = current;
    142. if (!queue.Contains(currentChild))
    143. {
    144. queue.Add(currentChild);
    145. }
    146. }
    147. }
    148. current.Visited = true;
    149. if (current.IsEnd)
    150. {
    151. return true;
    152. }
    153. }
    154. return false;
    155. }
    156. }
    157. public class Knoten
    158. {
    159. public bool IsStart { get; set; } = false;
    160. public bool IsShortestStart { get; set; } = false;
    161. public bool IsEnd { get; set; } = false;
    162. public Point Coordinates { get; set; } = Point.Empty;
    163. public bool Visited { get; set; } = false;
    164. public int ID { get; set; }
    165. public long? Cost { get; set; }
    166. public char Letter { get; set; }
    167. public int LastID { get; set; } = 0;
    168. public bool HasValidNeighbours { get; set; } = false;
    169. public Knoten LastKnoten { get; set; }
    170. public List<Verbindung> Verbindungen { get; set; } = new List<Verbindung>();
    171. }
    172. public class Verbindung
    173. {
    174. public long Cost { get; set; }
    175. public Knoten ConnectedKnoten { get; set; }
    176. }


    Tag 13 - C# Part 1 und 2
    Spoiler anzeigen

    Heute war recht easy - statt auf Newtonsoft.Json zu setzen ( weil FremdLib ) mal System.Text.Json benutzt. Ging ganz gut die Inputs konnte man schön einfach in Json laden und dann braucht man nur noch vergleichen.
    Ein wenig bei Microsoft gelesen wie man System.Text.Json so nutzten kann + die Default Comparer angeschaut. Wieder viel gelernt heute.

    C#-Quellcode

    1. using System.Text.Json;
    2. string[] lines = File.ReadAllLines("Input.txt").Where(x=> String.IsNullOrEmpty(x) == false).ToArray();
    3. List<Packet> leftPackets = new List<Packet>();
    4. List<Packet> rightPackets = new List<Packet>();
    5. int indexCounter = 0;
    6. List<int> pairIndexRightOrder = new List<int>();
    7. foreach (string[] pair in lines.Chunk(2))
    8. {
    9. string left = pair[0];
    10. string right = pair[1];
    11. JsonElement jsonLeft = JsonSerializer.Deserialize<JsonElement>(left);
    12. JsonElement jsonRight = JsonSerializer.Deserialize<JsonElement>(right);
    13. indexCounter++;
    14. Packet leftPacket = new Packet(indexCounter, jsonLeft);
    15. Packet rightPacket = new Packet(indexCounter, jsonRight);
    16. leftPackets.Add(leftPacket);
    17. rightPackets.Add(rightPacket);
    18. }
    19. List<Packet>.Enumerator leftPacketsArray = leftPackets.GetEnumerator();
    20. List<Packet>.Enumerator rightPacketsArray = rightPackets.GetEnumerator();
    21. while (leftPacketsArray.MoveNext() && rightPacketsArray.MoveNext())
    22. {
    23. Packet leftPacket = leftPacketsArray.Current;
    24. Packet rightPacket = rightPacketsArray.Current;
    25. if(Packet.ComparePackets(leftPacket.packet,rightPacket.packet)<0 )
    26. {
    27. pairIndexRightOrder.Add(leftPacket.Index);
    28. }
    29. }
    30. Console.WriteLine($"Part 1: {pairIndexRightOrder.Sum()}");
    31. List<Packet> packetsSorted = new List<Packet>();
    32. foreach (string[] pair in lines.Chunk(2))
    33. {
    34. string left = pair[0];
    35. string right = pair[1];
    36. JsonElement jsonLeft = JsonSerializer.Deserialize<JsonElement>(left);
    37. JsonElement jsonRight = JsonSerializer.Deserialize<JsonElement>(right);
    38. indexCounter++;
    39. Packet leftPacket = new Packet(indexCounter, jsonLeft);
    40. Packet rightPacket = new Packet(indexCounter, jsonRight);
    41. packetsSorted.Add(leftPacket);
    42. packetsSorted.Add(rightPacket);
    43. }
    44. JsonElement additionalPacketTwo = JsonSerializer.Deserialize<JsonElement>("[[2]]");
    45. JsonElement additionalPacketSix = JsonSerializer.Deserialize<JsonElement>("[[6]]");
    46. packetsSorted.Add( new Packet(2, additionalPacketTwo) );
    47. packetsSorted.Add( new Packet(4, additionalPacketSix) );
    48. Packet.SortPackets(packetsSorted);
    49. int additionalPacketTwoIndex = 0;
    50. int additionalPacketSixIndex = 0;
    51. int currentIndex = 1;
    52. foreach (Packet p in packetsSorted)
    53. {
    54. if (Packet.ComparePackets(p.packet, additionalPacketTwo) == 0)
    55. {
    56. additionalPacketTwoIndex = currentIndex;
    57. }
    58. if (Packet.ComparePackets(p.packet, additionalPacketSix) == 0)
    59. {
    60. additionalPacketSixIndex = currentIndex;
    61. }
    62. currentIndex++;
    63. }
    64. Console.WriteLine($"Part 2: {additionalPacketTwoIndex * additionalPacketSixIndex}");
    65. public class Packet
    66. {
    67. public JsonElement packet{ get; set; }
    68. public int Index { get; set; }
    69. public Packet(int index, JsonElement newPacket)
    70. {
    71. packet = newPacket;
    72. Index = index;
    73. }
    74. public static int ComparePackets(JsonElement leftPacket, JsonElement rightPacket)
    75. {
    76. JsonElement tmpPacket;
    77. if(leftPacket.ValueKind == JsonValueKind.Null && rightPacket.ValueKind != JsonValueKind.Null)
    78. {
    79. return -1;
    80. }
    81. if (leftPacket.ValueKind != JsonValueKind.Null && rightPacket.ValueKind == JsonValueKind.Null)
    82. {
    83. return 1;
    84. }
    85. if(leftPacket.ValueKind == JsonValueKind.Array && rightPacket.ValueKind == JsonValueKind.Number)
    86. {
    87. tmpPacket = JsonSerializer.Deserialize<JsonElement>("[" + rightPacket.GetInt32() + "]");
    88. return ComparePackets(leftPacket, tmpPacket);
    89. }
    90. if (leftPacket.ValueKind == JsonValueKind.Number && rightPacket.ValueKind == JsonValueKind.Array)
    91. {
    92. tmpPacket = JsonSerializer.Deserialize<JsonElement>("[" + leftPacket.GetInt32() + "]");
    93. return ComparePackets(tmpPacket, rightPacket);
    94. }
    95. if(leftPacket.ValueKind == JsonValueKind.Number && rightPacket.ValueKind == JsonValueKind.Number)
    96. {
    97. return Comparer<int>.Default.Compare(leftPacket.GetInt32(), rightPacket.GetInt32());
    98. }
    99. if(leftPacket.ValueKind == JsonValueKind.Array && rightPacket.ValueKind == JsonValueKind.Array)
    100. {
    101. JsonElement.ArrayEnumerator leftPacketArray = leftPacket.EnumerateArray();
    102. JsonElement.ArrayEnumerator rightPacketArray = rightPacket.EnumerateArray();
    103. while (leftPacketArray.MoveNext() && rightPacketArray.MoveNext())
    104. {
    105. JsonElement leftPacket2 = leftPacketArray.Current;
    106. JsonElement rightPacket2 = rightPacketArray.Current;
    107. int result = ComparePackets(leftPacket2, rightPacket2);
    108. if (result != 0)
    109. {
    110. return result;
    111. }
    112. }
    113. int countPackets = leftPacketArray.Count() - rightPacketArray.Count();
    114. if (countPackets == 0) return 0;
    115. if (countPackets < 0) return -1;
    116. return 1;
    117. }
    118. return 0;
    119. }
    120. public static void SortPackets(List<Packet> packets)
    121. {
    122. packets.Sort(Comparer);
    123. }
    124. public static int Comparer(Packet p1, Packet p2)
    125. {
    126. return Packet.ComparePackets(p1.packet, p2.packet);
    127. }
    128. }

    Grüße , xChRoNiKx

    Nützliche Links:
    Visual Studio Empfohlene Einstellungen | Try-Catch heißes Eisen

    Dieser Beitrag wurde bereits 1 mal editiert, zuletzt von „xChRoNiKx“ ()

    Leute viel Spaß noch, ich bin raus. Tag 12 könnte ich noch angehen, mit mehr Zeit. Wird mir im Moment zu viel.
    War schön Code von euch mit dem eigenen Zeug zu vergleichen. Und so ein zwei Sachen hab ich aufgeschnappt.

    Und an @BornToBeRoot
    PowerShell > C#
    war mir vorher auch nicht klar :thumbsup:
    codewars.com Rank: 4 kyu
    Day 12 to Day 15 and only the first task in each case.

    Day12

    C#-Quellcode

    1. private static void Part01()
    2. {
    3. //char lowlevel = 'a',mostlevel = 'z';
    4. char startsignal = 'S', endsignal = 'E';
    5. var steps = ToDijkstraShortPath(Source(), startsignal, endsignal);
    6. Console.WriteLine($"The goal is reached in {steps} steps.");
    7. Console.WriteLine();
    8. Console.ReadLine();
    9. }
    10. private static int ToDijkstraShortPath(string[] grid, char startsignal, char endsignal)
    11. {
    12. var queue = new Queue<PointEx>();
    13. var distances = ToDistances(grid);
    14. var endpoint = ToPoint(grid, endsignal);
    15. var startpoint = ToPoint(grid, startsignal);
    16. var elevations = ToElevations(grid, startsignal, endsignal, 'a');
    17. distances[startpoint] = 0;
    18. queue.Enqueue(new PointEx(startpoint, 0));
    19. while (queue.Count > 0)
    20. {
    21. var pointex = queue.Dequeue();
    22. var point = pointex.Point;
    23. if (point == endpoint)
    24. return distances[endpoint];
    25. foreach (var neighbor in ToNeighbors(elevations, point))
    26. {
    27. var distance = distances[point] + 1;
    28. if (distance < distances[neighbor])
    29. {
    30. distances[neighbor] = distance;
    31. queue.Enqueue(new PointEx(neighbor, distance));
    32. //queue = SortQueue(queue); // Is not required.
    33. }
    34. }
    35. }
    36. return distances[endpoint];
    37. }

    Methodes

    C#-Quellcode

    1. private static Queue<PointEx> SortQueue(Queue<PointEx> queue)
    2. {
    3. if (queue.Count < 2) return queue;
    4. //This is sufficient for smaller queues.
    5. var result = new Queue<PointEx>();
    6. var distance = 0;
    7. while (queue.Count > 0)
    8. {
    9. for (var i = 0; i < queue.Count; i++)
    10. {
    11. if (queue.ElementAt(i).Distance == distance)
    12. {
    13. result.Enqueue(queue.Dequeue());
    14. i--;
    15. }
    16. }
    17. distance++;
    18. }
    19. return result;
    20. }
    21. private static Point[] ToNeighbors(Dictionary<Point, int> elevations, Point point)
    22. {
    23. var c = point.X;
    24. var r = point.Y;
    25. //Without diagonals ..
    26. var result = new Point[]
    27. {
    28. new(c, r - 1), new(c, r + 1),
    29. new(c - 1, r), new(c + 1, r)
    30. };
    31. // .. and only points with diff-distance <= 1.
    32. // (0,0) = 0 is the current point, and therefore must not be used.
    33. var pointdistance = elevations[point];
    34. return result
    35. .Where(n => elevations
    36. .ContainsKey(n) && elevations[n] - pointdistance <= 1)
    37. .ToArray();
    38. }
    39. private static Dictionary<Point, int> ToElevations(
    40. string[] grid, char start, char end, char beginlevel)
    41. {
    42. var rlength = grid.Length;
    43. var clength = grid[0].Length;
    44. var result = new Dictionary<Point, int>();
    45. for (var r = 0; r < rlength; r++)
    46. for (var c = 0; c < clength; c++)
    47. if (grid[r][c] == start)
    48. result.Add(new Point(c, r), 0);
    49. else if (grid[r][c] == end)
    50. result.Add(new Point(c, r), 25);
    51. else result.Add(new Point(c, r), grid[r][c] - beginlevel);
    52. return result;
    53. }
    54. private static Dictionary<Point, int> ToDistances(string[] grid)
    55. {
    56. var rlength = grid.Length;
    57. var clength = grid[0].Length;
    58. var result = new Dictionary<Point, int>();
    59. for (var r = 0; r < rlength; r++)
    60. for (var c = 0; c < clength; c++)
    61. result.Add(new Point(c, r), int.MaxValue);
    62. return result;
    63. }
    64. private static Point ToPoint(string[] grid, char searchchar)
    65. {
    66. var rlength = grid.Length;
    67. var clength = grid[0].Length;
    68. for (var r = 0; r < rlength; r++)
    69. for (var c = 0; c < clength; c++)
    70. if (grid[r][c] == searchchar)
    71. return new Point(c, r);
    72. return new Point();
    73. }

    Class and Source

    C#-Quellcode

    1. private class PointEx
    2. {
    3. public Point Point { get; set; }
    4. public int Distance { get; set; } = int.MaxValue;
    5. public PointEx() { }
    6. public PointEx(int x, int y) { this.Point = new Point(x, y); }
    7. public PointEx(Point start, int distance)
    8. {
    9. this.Point = start;
    10. this.Distance = distance;
    11. }
    12. }
    13. private static string[] Source()
    14. {
    15. return new string[]
    16. {
    17. "Sabqponm",
    18. "abcryxxl",
    19. "accszExk",
    20. "acctuvwj",
    21. "abdefghi"
    22. };
    23. }

    Day13

    C#-Quellcode

    1. private static void Part01_B()
    2. {
    3. //Hab eine konventionelle Lösung mir gemacht, nur die
    4. //gefällt mir gar nicht, darum setze ich sie nicht hier rein.
    5. //Andere Möglichkeit mit Json. Bin jedoch noch nicht
    6. //so fit mit diesem Features.
    7. var jnodes = new List<JsonNode>();
    8. Array.ForEach(Source(), item =>
    9. {
    10. if (!string.IsNullOrEmpty(item))
    11. jnodes.Add(JsonNode.Parse(item));
    12. });
    13. //Habe jetzt einen geeigneten Comparer gefunden.
    14. var sum = jnodes
    15. .Chunk(2)
    16. .Select((pair, idx) =>
    17. Comparer(pair) < 0 ? idx + 1 : 0)
    18. .Sum();
    19. }

    Comparer

    C#-Quellcode

    1. private static int Comparer(JsonNode[] pair) =>
    2. Comparer(pair[0], pair[1]);
    3. private static int Comparer(JsonNode leftnode, JsonNode rightnode)
    4. {
    5. if (leftnode is JsonValue && rightnode is JsonValue)
    6. return (int)leftnode - (int)rightnode;
    7. JsonArray jsonarrayleft, jsonarrayright;
    8. if (leftnode is JsonArray)
    9. jsonarrayleft = leftnode.AsArray();
    10. else jsonarrayleft = new JsonArray((int)leftnode);
    11. if (rightnode is JsonArray)
    12. jsonarrayright = rightnode.AsArray();
    13. else jsonarrayright = new JsonArray((int)rightnode);
    14. var result = Enumerable.Zip(jsonarrayleft, jsonarrayright)
    15. //synchrone Weitergabe der jeweiligen X-Elemente beider Jsonarrays als pair.
    16. .Select(pair => Comparer(pair.First, pair.Second)); //recursiv
    17. return result.FirstOrDefault(x => x != 0, jsonarrayleft.Count - jsonarrayright.Count);
    18. }

    Source

    C#-Quellcode

    1. private static string[][] SourcePair()
    2. {
    3. return Source()
    4. .Where(str => !string.IsNullOrEmpty(str))
    5. .Chunk(2)
    6. .ToArray();
    7. }
    8. private static string[] Source()
    9. {
    10. return new string[]
    11. {
    12. "[1,1,3,1,1]",
    13. "[1,1,5,1,1]",
    14. "",
    15. "[[1],[2,3,4]]",
    16. "[[1],4]",
    17. "",
    18. "[9]",
    19. "[[8,7,6]]",
    20. "",
    21. "[[4,4],4,4]",
    22. "[[4,4],4,4,4]",
    23. "",
    24. "[7,7,7,7]",
    25. "[7,7,7]",
    26. "",
    27. "[]",
    28. "[3]",
    29. "",
    30. "[[[]]]",
    31. "[[]]",
    32. "",
    33. "[1,[2,[3,[4,[5,6,7]]]],8,9]",
    34. "[1,[2,[3,[4,[5,6,0]]]],8,9]",
    35. ""
    36. };
    37. }

    Day14

    C#-Quellcode

    1. public static void Part01()
    2. {
    3. //https://www.reddit.com/r/dailyprogrammer/comments/1rdtky/comment/cdma9n0/?utm_source=share&utm_medium=web2x&context=3
    4. var grid = new Dictionary<Point, char>();
    5. foreach (var item in Source())
    6. {
    7. var pts = item.Split(
    8. new string[] { " -> ", "," },
    9. StringSplitOptions.RemoveEmptyEntries)
    10. .Chunk(2)
    11. .Select(pair => new Point(int.Parse(pair[0]), int.Parse(pair[1])))
    12. .ToArray();
    13. for (var i = 1; i < pts.Length; i++)
    14. SetGridRocks(grid, pts[i - 1], pts[i]);
    15. }
    16. var maxy = grid.Keys.Select(pos => pos.Y).Max();
    17. var result = SetGridSands(grid, new Point(500, 0), maxy);
    18. Console.WriteLine($"There are {result} grains of sand come to rest");
    19. Console.WriteLine();
    20. Console.ReadLine();
    21. }

    Methodes

    C#-Quellcode

    1. private static Point Addition(Point p1, Point p2) =>
    2. new(p1.X + p2.X, p1.Y + p2.Y);
    3. private static int SetGridSands(
    4. Dictionary<Point, char> grid, Point sandpoint, int maxy)
    5. {
    6. while (true)
    7. {
    8. var current = DrawFallingSand(grid, sandpoint, maxy);
    9. if (grid.ContainsKey(current)) break;
    10. if (current.Y == maxy + 1) break;
    11. grid[current] = 'o';
    12. }
    13. return grid.Values.Count(x => x == 'o');
    14. }
    15. private static int SetGridRocks(
    16. Dictionary<Point, char> grid, Point start, Point end)
    17. {
    18. var count = 0;
    19. var step =
    20. new Point(Math.Sign(end.X - start.X), Math.Sign(end.Y - start.Y));
    21. var target = Addition(end, step);
    22. for (var p = start; p != target; p = Addition(p, step), count++)
    23. grid[p] = '#';
    24. return count;
    25. }
    26. private static Point DrawFallingSand(
    27. Dictionary<Point, char> grid, Point sandpoint, int maxy)
    28. {
    29. Point d = new(0, 1),
    30. l = new(-1, 1),
    31. r = new(1, 1);
    32. while (sandpoint.Y < maxy + 1)
    33. //Observe handing sequence. First down ...
    34. if (!grid.ContainsKey(Addition(sandpoint, d)))
    35. sandpoint = Addition(sandpoint, d);
    36. //than left ...
    37. else if (!grid.ContainsKey(Addition(sandpoint, l)))
    38. sandpoint = Addition(sandpoint, l);
    39. //then right ...
    40. else if (!grid.ContainsKey(Addition(sandpoint, r)))
    41. sandpoint = Addition(sandpoint, r);
    42. else break;
    43. return sandpoint;
    44. }

    Source

    C#-Quellcode

    1. private static string[] Source()
    2. {
    3. return new string[]
    4. {
    5. "498,4 -> 498,6 -> 496,6",
    6. "503,4 -> 502,4 -> 502,9 -> 494,9"
    7. };
    8. }

    Day15

    C#-Quellcode

    1. public static void Part01()
    2. {
    3. var src = Source();
    4. var rects = src.Select(pair => ToRect(pair)).ToArray();
    5. var left = rects.Select(rct => rct.Left).Min();
    6. var right = rects.Select(rct => rct.Right - 1).Max();
    7. var y = 10;
    8. var x = left;
    9. var result = 0;
    10. while (x <= right)
    11. {
    12. var visitpoint = new Point(x++, y);
    13. if (src.Any(pair =>
    14. pair[1] != visitpoint &&
    15. IsInGrid(pair, visitpoint)))
    16. result++;
    17. }
    18. Console.WriteLine($"In y = {y}, {result} positions cannot contain a beacon.");
    19. x = left;
    20. result = 0;
    21. y = 2_000_000;
    22. while (x <= right)
    23. {
    24. var visitpoint = new Point(x++, y);
    25. if (src.Any(pair =>
    26. pair[1] != visitpoint &&
    27. IsInGrid(pair, visitpoint)))
    28. result++;
    29. }
    30. Console.WriteLine($"In y = {y}, {result} positions cannot contain a beacon.");
    31. Console.WriteLine();
    32. Console.ReadLine();
    33. }​

    Methodes

    C#-Quellcode

    1. private static bool IsInGrid(Point[] pair, Point pos) =>
    2. ToMetric(pos, pair[0]) <= ToMetric(pair);
    3. private static Rectangle ToRect(Point[] pair) =>
    4. ToRect(pair[0], ToMetric(pair));
    5. private static Rectangle ToRect(Point sensor, int radius) =>
    6. new(sensor.X - radius, sensor.Y - radius, 2 * radius + 1, 2 * radius + 1);
    7. private static int ToMetric(Point[] pair) =>
    8. ToMetric(pair[0], pair[1]);
    9. private static int ToMetric(Point sensor, Point beacon) =>
    10. //https://en.wikipedia.org/wiki/Taxicab_geometry
    11. Math.Abs(sensor.X - beacon.X) + Math.Abs(sensor.Y - beacon.Y);​

    Source

    C#-Quellcode

    1. private static Point[][] Source()
    2. {
    3. return SourceText()
    4. .Select(line => line
    5. .Split(new string[] { "x=", ", ", "y=", ": ", },
    6. StringSplitOptions.RemoveEmptyEntries))
    7. .Select(split =>
    8. new Point[] {
    9. new(int.Parse(split[1]), int.Parse(split[2])),
    10. new(int.Parse(split[4]), int.Parse(split[5]))})
    11. .ToArray();
    12. }
    13. private static string[] SourceText()
    14. {
    15. return new string[]
    16. {
    17. "Sensor at x=2, y=18: closest beacon is at x=-2, y=15",
    18. "Sensor at x=9, y=16: closest beacon is at x=10, y=16",
    19. "Sensor at x=13, y=2: closest beacon is at x=15, y=3",
    20. "Sensor at x=12, y=14: closest beacon is at x=10, y=16",
    21. "Sensor at x=10, y=20: closest beacon is at x=10, y=16",
    22. "Sensor at x=14, y=17: closest beacon is at x=10, y=16",
    23. "Sensor at x=8, y=7: closest beacon is at x=2, y=10",
    24. "Sensor at x=2, y=0: closest beacon is at x=2, y=10",
    25. "Sensor at x=0, y=11: closest beacon is at x=2, y=10",
    26. "Sensor at x=20, y=14: closest beacon is at x=25, y=17",
    27. "Sensor at x=17, y=20: closest beacon is at x=21, y=22",
    28. "Sensor at x=16, y=7: closest beacon is at x=15, y=3",
    29. "Sensor at x=14, y=3: closest beacon is at x=15, y=3",
    30. "Sensor at x=20, y=1: closest beacon is at x=15, y=3",
    31. };
    32. }

    Dieser Beitrag wurde bereits 3 mal editiert, zuletzt von „exc-jdbi“ ()

    Ein bischen verspätet, aber vielen Dank, für alle Leute die mitgemacht haben.
    Es war wirklich Spaßig.

    Ich war zwar nur bis Tag 7 oder so dabei, aber die hab ich gefeiert.
    Außerdem finde ich es schön das es jetzt so viele Beispiele gibt, an denen sich Leute möglicherweiße ein wenig orientieren können? Wer weiß?

    Ich hoffe nächstes Jahr halte ich länger durch, aber frohe verspätete Weihnachtswünsche! (Dann halt schon mal für's nächste Jahr)
    ----------------------------------------------------------------------------------------------------------------------

    Hier könnte meine Signatur stehen, aber die ist mir abfußen gekommen.

    ----------------------------------------------------------------------------------------------------------------------