Advent of Code 2022
Sie verwenden einen veralteten Browser (%browser%) mit Sicherheitsschwachstellen und können nicht alle Funktionen dieser Webseite nutzen.
Hier erfahren Sie, wie einfach Sie Ihren Browser aktualisieren können.
Hier erfahren Sie, wie einfach Sie Ihren Browser aktualisieren können.
Es gibt 85 Antworten in diesem Thema. Der letzte Beitrag () ist von Elanda.
-
-
Day 12:
Spoiler anzeigen
C#-Quellcode
- [b]
- [/b]namespace Twelve;
- using System.Diagnostics;
- using System.Numerics;
- public class Program
- {
- static Grid _grid = null;
- static void Main(string[] args)
- {
- IEnumerable<string> data = File.ReadAllLines("input.txt");
- _grid = new Grid(data);
- Log(_grid.FindAPathAtAll(1));
- Log(_grid.FindAPathAtAll(2));
- }
- static void Log(object message) => Console.WriteLine(message);
- }
- class Node
- {
- public int X { get; set; }
- public int Y { get; set; }
- public char Value { get; set; }
- public int Distance { get; set; }
- public int NextDistance { get; set; }
- public Node(int x, int y, char value) => (x, y, value) = (this.X = x, this.Y = y, this.Value = value);
- }
- class Grid
- {
- public Node[,] Nodes { get; set; }
- private Node _startNode = null;
- private Node _endNode = null;
- public Grid(IEnumerable<string> data)
- {
- this.Nodes = new Node[data.ElementAt(0).Count(), data.Count()];
- for (int y = 0; y < data.Count(); y++)
- for (int x = 0; x < data.ElementAt(0).Count(); x++)
- {
- this.Nodes[x, y] = new Node(x, y, data.ElementAt(y).ElementAt(x));
- if (data.ElementAt(y).ElementAt(x) == 'S')
- {
- _startNode = this.Nodes[x, y];
- this.Nodes[x, y].Value = 'a';
- }
- if (data.ElementAt(y).ElementAt(x) == 'E')
- {
- _endNode = this.Nodes[x, y];
- this.Nodes[x, y].Value = 'z';
- }
- this.Nodes[x, y].Distance = 0;
- }
- }
- //"Wave-propagation algo
- public int FindAPathAtAll(int part)
- {
- List<Node> workingNodes = new();
- _endNode.NextDistance = 1;
- workingNodes.Add(_endNode);
- while (true)
- {
- List<Node> newNodes = new();
- foreach (var node in workingNodes)
- {
- node.Distance = node.NextDistance;
- var neighbours = GetNeighbours(node);
- foreach (var neighbour in neighbours)
- {
- if (neighbour.Distance != 0) continue;
- if (node.Value - neighbour.Value < 2)
- {
- neighbour.NextDistance = node.Distance + 1;
- newNodes.Add(neighbour);
- }
- }
- }
- if (newNodes.Count == 0) break;
- workingNodes.Clear();
- workingNodes.AddRange(newNodes.Distinct().ToList());
- }
- if (part == 1) return _startNode.Distance - 1;
- if (part == 2)
- {
- int min = int.MaxValue;
- foreach (var node in this.Nodes)
- {
- if (node.Value == 'a' && node.Distance != 0 && node.Distance < min)
- min = node.Distance - 1;
- }
- return min;
- }
- return 0;
- }
- public List<Node> GetNeighbours(Node node)
- {
- List<Node> result = new();
- if (IsOnGrid(node.X - 1, node.Y))
- result.Add(this.Nodes[node.X - 1, node.Y]);
- if (IsOnGrid(node.X + 1, node.Y))
- result.Add(this.Nodes[node.X + 1, node.Y]);
- if (IsOnGrid(node.X, node.Y - 1))
- result.Add(this.Nodes[node.X, node.Y - 1]);
- if (IsOnGrid(node.X, node.Y + 1))
- result.Add(this.Nodes[node.X, node.Y + 1]);
- return result;
- }
- public Node GetNode(int x, int y)
- {
- if (IsOnGrid(x, y))
- return this.Nodes[x, y];
- return null;
- }
- public bool IsOnGrid(int x, int y)
- {
- return (x >= 0 && x < this.Nodes.GetLength(0) &&
- y >= 0 && y < this.Nodes.GetLength(1));
- }
- public bool IsOnGrid(Node node) => IsOnGrid(node.X, node.Y);
- }
Die Unendlichkeit ist weit. Vor allem gegen Ende.
Manche Menschen sind gar nicht dumm. Sie haben nur Pech beim Denken. -
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
- using System.Drawing;
- string[] lines = File.ReadAllLines("Input.txt");
- Map map2 = new Map(lines);
- map2.Initilize();
- map2.CalculateNeighbours();
- map2.getShortestPathFromStartingNode(map2.Nodes.FirstOrDefault(x => x.IsStart == true));
- List<long> shortestPaths = new List<long>();
- long shortestPathCost = 0;
- shortestPathCost = 0;
- List<Knoten> kleinsterweg = new List<Knoten>();
- kleinsterweg.Add(map2.Nodes.FirstOrDefault(x => x.IsEnd));
- getShortestPath(kleinsterweg, map2.Nodes.FirstOrDefault(x => x.IsEnd));
- Console.WriteLine($"Part 1: {kleinsterweg.Count() - 1}");
- Console.WriteLine($"checking {map2.Nodes.Where(x => x.Letter == 'a').Count()} Nodes for Part 2");
- int counter = 0;
- Parallel.ForEach(map2.Nodes.Where(x => x.Letter == 'a' && x.HasValidNeighbours == true), k =>
- {
- Map map = new Map(lines);
- map.Initilize();
- map.CalculateNeighbours();
- if (!map.getShortestPathFromStartingNode(map.Nodes.FirstOrDefault(x=>x.ID == k.ID))) return;
- shortestPathCost = 0;
- List<Knoten> kleinsterweg = new List<Knoten>();
- kleinsterweg.Add(map.Nodes.FirstOrDefault(x => x.IsEnd));
- getShortestPath(kleinsterweg, map.Nodes.FirstOrDefault(x => x.IsEnd));
- shortestPaths.Add(kleinsterweg.Count());
- });
- Console.WriteLine($"Part 2: {shortestPaths.Min()}");
- void getShortestPath(List<Knoten> tkn, Knoten node)
- {
- if (node.LastKnoten == null) return;
- tkn.Add(node.LastKnoten);
- shortestPathCost += node.Verbindungen.FirstOrDefault(x => x.ConnectedKnoten.ID == node.LastKnoten.ID).Cost;
- getShortestPath(tkn, node.LastKnoten);
- }
- Console.WriteLine("fertig");
- public class Map
- {
- public List<Knoten> Nodes { get; set; } = new List<Knoten>();
- public int Rows { get; set; }
- public int Cols { get; set; }
- public string[] Grid { get; private set; }
- public Map(string[] lines)
- {
- Rows = lines.Count();
- Cols = lines[0].Length;
- Grid = lines;
- }
- public void Initilize()
- {
- int knotenId = 0;
- for (int i = 0; i < Rows; i++)
- {
- for (int x = 0; x < Cols; x++)
- {
- Knoten k = new Knoten();
- int actual = Grid[i][x];
- k.Letter = (char)actual;
- if ((char)actual == 'S')
- {
- k.Letter = 'a';
- k.IsStart = true;
- k.Cost = 0;
- }
- if ((char)actual == 'E')
- {
- k.Letter = 'z';
- k.IsEnd = true;
- }
- k.ID = knotenId;
- k.Coordinates = new Point(i, x);
- knotenId++;
- Nodes.Add(k);
- }
- }
- }
- public void CalculateNeighbours()
- {
- foreach (Knoten k in Nodes)
- {
- Knoten kUp = Nodes.FirstOrDefault(x => x.Coordinates.X == k.Coordinates.X - 1 && x.Coordinates.Y == k.Coordinates.Y);
- Knoten kDown = Nodes.FirstOrDefault(x => x.Coordinates.X == k.Coordinates.X + 1 && x.Coordinates.Y == k.Coordinates.Y);
- Knoten kLeft = Nodes.FirstOrDefault(x => x.Coordinates.X == k.Coordinates.X && x.Coordinates.Y == k.Coordinates.Y - 1);
- Knoten kRight = Nodes.FirstOrDefault(x => x.Coordinates.X == k.Coordinates.X && x.Coordinates.Y == k.Coordinates.Y + 1);
- int result = 0;
- if (kUp != null)
- {
- result = ((k.Letter + 1) >= kUp.Letter) ? 1 : 9999;
- if (result < 9999) k.HasValidNeighbours = true;
- Verbindung v = new Verbindung();
- v.Cost = result;
- v.ConnectedKnoten = kUp;
- k.Verbindungen.Add(v);
- }
- if (kDown != null)
- {
- result = ((k.Letter + 1) >= kDown.Letter) ? 1 : 9999;
- if (result < 9999) k.HasValidNeighbours = true;
- Verbindung v = new Verbindung();
- v.Cost = result;
- v.ConnectedKnoten = kDown;
- k.Verbindungen.Add(v);
- }
- if (kLeft != null)
- {
- result = ((k.Letter + 1) >= kLeft.Letter) ? 1 : 9999;
- if (result < 9999) k.HasValidNeighbours = true;
- Verbindung v = new Verbindung();
- v.Cost = result;
- v.ConnectedKnoten = kLeft;
- k.Verbindungen.Add(v);
- }
- if (kRight != null)
- {
- result = ((k.Letter + 1) >= kRight.Letter) ? 1 : 9999;
- if (result < 9999) k.HasValidNeighbours = true;
- Verbindung v = new Verbindung();
- v.Cost = result;
- v.ConnectedKnoten = kRight;
- k.Verbindungen.Add(v);
- }
- }
- }
- public bool getShortestPathFromStartingNode(Knoten start)
- {
- List<Knoten> queue = new List<Knoten>();
- queue.Add(start);
- while (queue.Any())
- {
- Knoten current = queue.OrderBy(x => x.Cost).ToList().First();
- queue.Remove(current);
- foreach (Verbindung currentConnection in current.Verbindungen.OrderBy(x => x.Cost))
- {
- Knoten currentChild = currentConnection.ConnectedKnoten;
- if (currentChild.Visited) continue;
- if (currentChild.Letter > current.Letter + 1) continue;
- if (currentChild.Cost == null || current.Cost + currentConnection.Cost < currentChild.Cost)
- {
- currentChild.Cost = current.Cost + currentConnection.Cost;
- currentChild.LastID = current.ID;
- currentChild.LastKnoten = current;
- if (!queue.Contains(currentChild))
- {
- queue.Add(currentChild);
- }
- }
- }
- current.Visited = true;
- if (current.IsEnd)
- {
- return true;
- }
- }
- return false;
- }
- }
- public class Knoten
- {
- public bool IsStart { get; set; } = false;
- public bool IsShortestStart { get; set; } = false;
- public bool IsEnd { get; set; } = false;
- public Point Coordinates { get; set; } = Point.Empty;
- public bool Visited { get; set; } = false;
- public int ID { get; set; }
- public long? Cost { get; set; }
- public char Letter { get; set; }
- public int LastID { get; set; } = 0;
- public bool HasValidNeighbours { get; set; } = false;
- public Knoten LastKnoten { get; set; }
- public List<Verbindung> Verbindungen { get; set; } = new List<Verbindung>();
- }
- public class Verbindung
- {
- public long Cost { get; set; }
- public Knoten ConnectedKnoten { get; set; }
- }
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
- using System.Text.Json;
- string[] lines = File.ReadAllLines("Input.txt").Where(x=> String.IsNullOrEmpty(x) == false).ToArray();
- List<Packet> leftPackets = new List<Packet>();
- List<Packet> rightPackets = new List<Packet>();
- int indexCounter = 0;
- List<int> pairIndexRightOrder = new List<int>();
- foreach (string[] pair in lines.Chunk(2))
- {
- string left = pair[0];
- string right = pair[1];
- JsonElement jsonLeft = JsonSerializer.Deserialize<JsonElement>(left);
- JsonElement jsonRight = JsonSerializer.Deserialize<JsonElement>(right);
- indexCounter++;
- Packet leftPacket = new Packet(indexCounter, jsonLeft);
- Packet rightPacket = new Packet(indexCounter, jsonRight);
- leftPackets.Add(leftPacket);
- rightPackets.Add(rightPacket);
- }
- List<Packet>.Enumerator leftPacketsArray = leftPackets.GetEnumerator();
- List<Packet>.Enumerator rightPacketsArray = rightPackets.GetEnumerator();
- while (leftPacketsArray.MoveNext() && rightPacketsArray.MoveNext())
- {
- Packet leftPacket = leftPacketsArray.Current;
- Packet rightPacket = rightPacketsArray.Current;
- if(Packet.ComparePackets(leftPacket.packet,rightPacket.packet)<0 )
- {
- pairIndexRightOrder.Add(leftPacket.Index);
- }
- }
- Console.WriteLine($"Part 1: {pairIndexRightOrder.Sum()}");
- List<Packet> packetsSorted = new List<Packet>();
- foreach (string[] pair in lines.Chunk(2))
- {
- string left = pair[0];
- string right = pair[1];
- JsonElement jsonLeft = JsonSerializer.Deserialize<JsonElement>(left);
- JsonElement jsonRight = JsonSerializer.Deserialize<JsonElement>(right);
- indexCounter++;
- Packet leftPacket = new Packet(indexCounter, jsonLeft);
- Packet rightPacket = new Packet(indexCounter, jsonRight);
- packetsSorted.Add(leftPacket);
- packetsSorted.Add(rightPacket);
- }
- JsonElement additionalPacketTwo = JsonSerializer.Deserialize<JsonElement>("[[2]]");
- JsonElement additionalPacketSix = JsonSerializer.Deserialize<JsonElement>("[[6]]");
- packetsSorted.Add( new Packet(2, additionalPacketTwo) );
- packetsSorted.Add( new Packet(4, additionalPacketSix) );
- Packet.SortPackets(packetsSorted);
- int additionalPacketTwoIndex = 0;
- int additionalPacketSixIndex = 0;
- int currentIndex = 1;
- foreach (Packet p in packetsSorted)
- {
- if (Packet.ComparePackets(p.packet, additionalPacketTwo) == 0)
- {
- additionalPacketTwoIndex = currentIndex;
- }
- if (Packet.ComparePackets(p.packet, additionalPacketSix) == 0)
- {
- additionalPacketSixIndex = currentIndex;
- }
- currentIndex++;
- }
- Console.WriteLine($"Part 2: {additionalPacketTwoIndex * additionalPacketSixIndex}");
- public class Packet
- {
- public JsonElement packet{ get; set; }
- public int Index { get; set; }
- public Packet(int index, JsonElement newPacket)
- {
- packet = newPacket;
- Index = index;
- }
- public static int ComparePackets(JsonElement leftPacket, JsonElement rightPacket)
- {
- JsonElement tmpPacket;
- if(leftPacket.ValueKind == JsonValueKind.Null && rightPacket.ValueKind != JsonValueKind.Null)
- {
- return -1;
- }
- if (leftPacket.ValueKind != JsonValueKind.Null && rightPacket.ValueKind == JsonValueKind.Null)
- {
- return 1;
- }
- if(leftPacket.ValueKind == JsonValueKind.Array && rightPacket.ValueKind == JsonValueKind.Number)
- {
- tmpPacket = JsonSerializer.Deserialize<JsonElement>("[" + rightPacket.GetInt32() + "]");
- return ComparePackets(leftPacket, tmpPacket);
- }
- if (leftPacket.ValueKind == JsonValueKind.Number && rightPacket.ValueKind == JsonValueKind.Array)
- {
- tmpPacket = JsonSerializer.Deserialize<JsonElement>("[" + leftPacket.GetInt32() + "]");
- return ComparePackets(tmpPacket, rightPacket);
- }
- if(leftPacket.ValueKind == JsonValueKind.Number && rightPacket.ValueKind == JsonValueKind.Number)
- {
- return Comparer<int>.Default.Compare(leftPacket.GetInt32(), rightPacket.GetInt32());
- }
- if(leftPacket.ValueKind == JsonValueKind.Array && rightPacket.ValueKind == JsonValueKind.Array)
- {
- JsonElement.ArrayEnumerator leftPacketArray = leftPacket.EnumerateArray();
- JsonElement.ArrayEnumerator rightPacketArray = rightPacket.EnumerateArray();
- while (leftPacketArray.MoveNext() && rightPacketArray.MoveNext())
- {
- JsonElement leftPacket2 = leftPacketArray.Current;
- JsonElement rightPacket2 = rightPacketArray.Current;
- int result = ComparePackets(leftPacket2, rightPacket2);
- if (result != 0)
- {
- return result;
- }
- }
- int countPackets = leftPacketArray.Count() - rightPacketArray.Count();
- if (countPackets == 0) return 0;
- if (countPackets < 0) return -1;
- return 1;
- }
- return 0;
- }
- public static void SortPackets(List<Packet> packets)
- {
- packets.Sort(Comparer);
- }
- public static int Comparer(Packet p1, Packet p2)
- {
- return Packet.ComparePackets(p1.packet, p2.packet);
- }
- }
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 klarcodewars.com Rank: 4 kyu -
Day 12 to Day 15 and only the first task in each case.
Day12 C#-Quellcode
- private static void Part01()
- {
- //char lowlevel = 'a',mostlevel = 'z';
- char startsignal = 'S', endsignal = 'E';
- var steps = ToDijkstraShortPath(Source(), startsignal, endsignal);
- Console.WriteLine($"The goal is reached in {steps} steps.");
- Console.WriteLine();
- Console.ReadLine();
- }
- private static int ToDijkstraShortPath(string[] grid, char startsignal, char endsignal)
- {
- var queue = new Queue<PointEx>();
- var distances = ToDistances(grid);
- var endpoint = ToPoint(grid, endsignal);
- var startpoint = ToPoint(grid, startsignal);
- var elevations = ToElevations(grid, startsignal, endsignal, 'a');
- distances[startpoint] = 0;
- queue.Enqueue(new PointEx(startpoint, 0));
- while (queue.Count > 0)
- {
- var pointex = queue.Dequeue();
- var point = pointex.Point;
- if (point == endpoint)
- return distances[endpoint];
- foreach (var neighbor in ToNeighbors(elevations, point))
- {
- var distance = distances[point] + 1;
- if (distance < distances[neighbor])
- {
- distances[neighbor] = distance;
- queue.Enqueue(new PointEx(neighbor, distance));
- //queue = SortQueue(queue); // Is not required.
- }
- }
- }
- return distances[endpoint];
- }
Methodes C#-Quellcode
- private static Queue<PointEx> SortQueue(Queue<PointEx> queue)
- {
- if (queue.Count < 2) return queue;
- //This is sufficient for smaller queues.
- var result = new Queue<PointEx>();
- var distance = 0;
- while (queue.Count > 0)
- {
- for (var i = 0; i < queue.Count; i++)
- {
- if (queue.ElementAt(i).Distance == distance)
- {
- result.Enqueue(queue.Dequeue());
- i--;
- }
- }
- distance++;
- }
- return result;
- }
- private static Point[] ToNeighbors(Dictionary<Point, int> elevations, Point point)
- {
- var c = point.X;
- var r = point.Y;
- //Without diagonals ..
- var result = new Point[]
- {
- new(c, r - 1), new(c, r + 1),
- new(c - 1, r), new(c + 1, r)
- };
- // .. and only points with diff-distance <= 1.
- // (0,0) = 0 is the current point, and therefore must not be used.
- var pointdistance = elevations[point];
- return result
- .Where(n => elevations
- .ContainsKey(n) && elevations[n] - pointdistance <= 1)
- .ToArray();
- }
- private static Dictionary<Point, int> ToElevations(
- string[] grid, char start, char end, char beginlevel)
- {
- var rlength = grid.Length;
- var clength = grid[0].Length;
- var result = new Dictionary<Point, int>();
- for (var r = 0; r < rlength; r++)
- for (var c = 0; c < clength; c++)
- if (grid[r][c] == start)
- result.Add(new Point(c, r), 0);
- else if (grid[r][c] == end)
- result.Add(new Point(c, r), 25);
- else result.Add(new Point(c, r), grid[r][c] - beginlevel);
- return result;
- }
- private static Dictionary<Point, int> ToDistances(string[] grid)
- {
- var rlength = grid.Length;
- var clength = grid[0].Length;
- var result = new Dictionary<Point, int>();
- for (var r = 0; r < rlength; r++)
- for (var c = 0; c < clength; c++)
- result.Add(new Point(c, r), int.MaxValue);
- return result;
- }
- private static Point ToPoint(string[] grid, char searchchar)
- {
- var rlength = grid.Length;
- var clength = grid[0].Length;
- for (var r = 0; r < rlength; r++)
- for (var c = 0; c < clength; c++)
- if (grid[r][c] == searchchar)
- return new Point(c, r);
- return new Point();
- }
Class and Source C#-Quellcode
- private class PointEx
- {
- public Point Point { get; set; }
- public int Distance { get; set; } = int.MaxValue;
- public PointEx() { }
- public PointEx(int x, int y) { this.Point = new Point(x, y); }
- public PointEx(Point start, int distance)
- {
- this.Point = start;
- this.Distance = distance;
- }
- }
- private static string[] Source()
- {
- return new string[]
- {
- "Sabqponm",
- "abcryxxl",
- "accszExk",
- "acctuvwj",
- "abdefghi"
- };
- }
Day13 C#-Quellcode
- private static void Part01_B()
- {
- //Hab eine konventionelle Lösung mir gemacht, nur die
- //gefällt mir gar nicht, darum setze ich sie nicht hier rein.
- //Andere Möglichkeit mit Json. Bin jedoch noch nicht
- //so fit mit diesem Features.
- var jnodes = new List<JsonNode>();
- Array.ForEach(Source(), item =>
- {
- if (!string.IsNullOrEmpty(item))
- jnodes.Add(JsonNode.Parse(item));
- });
- //Habe jetzt einen geeigneten Comparer gefunden.
- var sum = jnodes
- .Chunk(2)
- .Select((pair, idx) =>
- Comparer(pair) < 0 ? idx + 1 : 0)
- .Sum();
- }
Comparer C#-Quellcode
- private static int Comparer(JsonNode[] pair) =>
- Comparer(pair[0], pair[1]);
- private static int Comparer(JsonNode leftnode, JsonNode rightnode)
- {
- if (leftnode is JsonValue && rightnode is JsonValue)
- return (int)leftnode - (int)rightnode;
- JsonArray jsonarrayleft, jsonarrayright;
- if (leftnode is JsonArray)
- jsonarrayleft = leftnode.AsArray();
- else jsonarrayleft = new JsonArray((int)leftnode);
- if (rightnode is JsonArray)
- jsonarrayright = rightnode.AsArray();
- else jsonarrayright = new JsonArray((int)rightnode);
- var result = Enumerable.Zip(jsonarrayleft, jsonarrayright)
- //synchrone Weitergabe der jeweiligen X-Elemente beider Jsonarrays als pair.
- .Select(pair => Comparer(pair.First, pair.Second)); //recursiv
- return result.FirstOrDefault(x => x != 0, jsonarrayleft.Count - jsonarrayright.Count);
- }
Source C#-Quellcode
- private static string[][] SourcePair()
- {
- return Source()
- .Where(str => !string.IsNullOrEmpty(str))
- .Chunk(2)
- .ToArray();
- }
- private static string[] Source()
- {
- return new string[]
- {
- "[1,1,3,1,1]",
- "[1,1,5,1,1]",
- "",
- "[[1],[2,3,4]]",
- "[[1],4]",
- "",
- "[9]",
- "[[8,7,6]]",
- "",
- "[[4,4],4,4]",
- "[[4,4],4,4,4]",
- "",
- "[7,7,7,7]",
- "[7,7,7]",
- "",
- "[]",
- "[3]",
- "",
- "[[[]]]",
- "[[]]",
- "",
- "[1,[2,[3,[4,[5,6,7]]]],8,9]",
- "[1,[2,[3,[4,[5,6,0]]]],8,9]",
- ""
- };
- }
Day14 C#-Quellcode
- public static void Part01()
- {
- //https://www.reddit.com/r/dailyprogrammer/comments/1rdtky/comment/cdma9n0/?utm_source=share&utm_medium=web2x&context=3
- var grid = new Dictionary<Point, char>();
- foreach (var item in Source())
- {
- var pts = item.Split(
- new string[] { " -> ", "," },
- StringSplitOptions.RemoveEmptyEntries)
- .Chunk(2)
- .Select(pair => new Point(int.Parse(pair[0]), int.Parse(pair[1])))
- .ToArray();
- for (var i = 1; i < pts.Length; i++)
- SetGridRocks(grid, pts[i - 1], pts[i]);
- }
- var maxy = grid.Keys.Select(pos => pos.Y).Max();
- var result = SetGridSands(grid, new Point(500, 0), maxy);
- Console.WriteLine($"There are {result} grains of sand come to rest");
- Console.WriteLine();
- Console.ReadLine();
- }
Methodes C#-Quellcode
- private static Point Addition(Point p1, Point p2) =>
- new(p1.X + p2.X, p1.Y + p2.Y);
- private static int SetGridSands(
- Dictionary<Point, char> grid, Point sandpoint, int maxy)
- {
- while (true)
- {
- var current = DrawFallingSand(grid, sandpoint, maxy);
- if (grid.ContainsKey(current)) break;
- if (current.Y == maxy + 1) break;
- grid[current] = 'o';
- }
- return grid.Values.Count(x => x == 'o');
- }
- private static int SetGridRocks(
- Dictionary<Point, char> grid, Point start, Point end)
- {
- var count = 0;
- var step =
- new Point(Math.Sign(end.X - start.X), Math.Sign(end.Y - start.Y));
- var target = Addition(end, step);
- for (var p = start; p != target; p = Addition(p, step), count++)
- grid[p] = '#';
- return count;
- }
- private static Point DrawFallingSand(
- Dictionary<Point, char> grid, Point sandpoint, int maxy)
- {
- Point d = new(0, 1),
- l = new(-1, 1),
- r = new(1, 1);
- while (sandpoint.Y < maxy + 1)
- //Observe handing sequence. First down ...
- if (!grid.ContainsKey(Addition(sandpoint, d)))
- sandpoint = Addition(sandpoint, d);
- //than left ...
- else if (!grid.ContainsKey(Addition(sandpoint, l)))
- sandpoint = Addition(sandpoint, l);
- //then right ...
- else if (!grid.ContainsKey(Addition(sandpoint, r)))
- sandpoint = Addition(sandpoint, r);
- else break;
- return sandpoint;
- }
Day15 C#-Quellcode
- public static void Part01()
- {
- var src = Source();
- var rects = src.Select(pair => ToRect(pair)).ToArray();
- var left = rects.Select(rct => rct.Left).Min();
- var right = rects.Select(rct => rct.Right - 1).Max();
- var y = 10;
- var x = left;
- var result = 0;
- while (x <= right)
- {
- var visitpoint = new Point(x++, y);
- if (src.Any(pair =>
- pair[1] != visitpoint &&
- IsInGrid(pair, visitpoint)))
- result++;
- }
- Console.WriteLine($"In y = {y}, {result} positions cannot contain a beacon.");
- x = left;
- result = 0;
- y = 2_000_000;
- while (x <= right)
- {
- var visitpoint = new Point(x++, y);
- if (src.Any(pair =>
- pair[1] != visitpoint &&
- IsInGrid(pair, visitpoint)))
- result++;
- }
- Console.WriteLine($"In y = {y}, {result} positions cannot contain a beacon.");
- Console.WriteLine();
- Console.ReadLine();
- }
Methodes C#-Quellcode
- private static bool IsInGrid(Point[] pair, Point pos) =>
- ToMetric(pos, pair[0]) <= ToMetric(pair);
- private static Rectangle ToRect(Point[] pair) =>
- ToRect(pair[0], ToMetric(pair));
- private static Rectangle ToRect(Point sensor, int radius) =>
- new(sensor.X - radius, sensor.Y - radius, 2 * radius + 1, 2 * radius + 1);
- private static int ToMetric(Point[] pair) =>
- ToMetric(pair[0], pair[1]);
- private static int ToMetric(Point sensor, Point beacon) =>
- //https://en.wikipedia.org/wiki/Taxicab_geometry
- Math.Abs(sensor.X - beacon.X) + Math.Abs(sensor.Y - beacon.Y);
Source C#-Quellcode
- private static Point[][] Source()
- {
- return SourceText()
- .Select(line => line
- .Split(new string[] { "x=", ", ", "y=", ": ", },
- StringSplitOptions.RemoveEmptyEntries))
- .Select(split =>
- new Point[] {
- new(int.Parse(split[1]), int.Parse(split[2])),
- new(int.Parse(split[4]), int.Parse(split[5]))})
- .ToArray();
- }
- private static string[] SourceText()
- {
- return new string[]
- {
- "Sensor at x=2, y=18: closest beacon is at x=-2, y=15",
- "Sensor at x=9, y=16: closest beacon is at x=10, y=16",
- "Sensor at x=13, y=2: closest beacon is at x=15, y=3",
- "Sensor at x=12, y=14: closest beacon is at x=10, y=16",
- "Sensor at x=10, y=20: closest beacon is at x=10, y=16",
- "Sensor at x=14, y=17: closest beacon is at x=10, y=16",
- "Sensor at x=8, y=7: closest beacon is at x=2, y=10",
- "Sensor at x=2, y=0: closest beacon is at x=2, y=10",
- "Sensor at x=0, y=11: closest beacon is at x=2, y=10",
- "Sensor at x=20, y=14: closest beacon is at x=25, y=17",
- "Sensor at x=17, y=20: closest beacon is at x=21, y=22",
- "Sensor at x=16, y=7: closest beacon is at x=15, y=3",
- "Sensor at x=14, y=3: closest beacon is at x=15, y=3",
- "Sensor at x=20, y=1: closest beacon is at x=15, y=3",
- };
- }
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.
----------------------------------------------------------------------------------------------------------------------
-
Ähnliche Themen
-
FinnSoft - - Off-Topic
-
13 Benutzer haben hier geschrieben
- nogood (16)
- xChRoNiKx (14)
- Elanda (13)
- exc-jdbi (8)
- BitBrösel (8)
- ISliceUrPanties (7)
- EaranMaleasi (6)
- SpaceyX (5)
- BornToBeRoot (4)
- shad (2)
- mrMo (1)
- Marcus Gräfe (1)
- Joshi (1)