Advent of Code 2022

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

    Lösung Tag 7 in PowerShell ;)

    Spoiler anzeigen

    Quellcode

    1. [System.Collections.ArrayList]$Folders = @()
    2. $CurrentFolder = ""
    3. foreach ($Line in Get-Content -Path $PSScriptRoot\day07_input.txt) {
    4. if ($Line.StartsWith("$ cd")) {
    5. $CommandArray = $Line.Split(" ")
    6. switch ($CommandArray[2]) {
    7. "/" { $CurrentFolder = $CommandArray[2] }
    8. ".." { $CurrentFolder = $CurrentFolder.Substring(0, $CurrentFolder.TrimEnd("/").LastIndexOf("/")) + "/" }
    9. default { $CurrentFolder += $CommandArray[2] + "/" }
    10. }
    11. }
    12. elseif (-not $Line.StartsWith("$")) {
    13. $FileOrDir = $Line.Trim().Split(" ")
    14. if ($FileOrDir -match "^\d+$") {
    15. $FileSize = [int]$FileOrDir[0]
    16. $TempFolder = ""
    17. $PathSplit = $CurrentFolder.Split("/")
    18. foreach ($Sub in $PathSplit[0..($PathSplit.Count - 2)]) {
    19. $TempFolder += $Sub + "/"
    20. $x = $Folders | Where-Object { $_.Folder -eq $TempFolder }
    21. $TempSize = $FileSize
    22. # Remove existing entry / update
    23. if ($null -ne $x) {
    24. $TempSize += $x.Size
    25. [void]$Folders.Remove($x)
    26. }
    27. [void]$Folders.Add([pscustomobject]@{
    28. Folder = $TempFolder
    29. Size = $TempSize
    30. })
    31. }
    32. }
    33. }
    34. }
    35. # Part 1
    36. ($Folders | Where-Object { $_.Size -le 100000 } | Measure-Object -Sum Size).Sum
    37. # Part 2
    38. $DiffFreeSpace = 70000000 - ($Folders | Where-Object { $_.Folder -eq "/" }).Size
    39. $RequiredSpace = (30000000 - $DiffFreeSpace)
    40. ($Folders | Where-Object { $_.Size -ge $RequiredSpace } | Sort-Object -Property Size | Select-Object -First 1).Size


    Alle meine Lösungen für PowerShell findet ihr auf GitHub: github.com/BornToBeRoot/AdventOfCode
    NETworkManager - A powerful tool for managing networks and troubleshoot network problems!
    Tag 07 C# Part 1 und 2
    Da gibt es nen kleines Ding was man beachten sollte.. habs mal kommentiert aber nicht wirklich ausführlich.
    Spoiler anzeigen

    C#-Quellcode

    1. string[] commands = System.IO.File.ReadAllLines("Input.txt");
    2. Directory RootDirectory = new Directory("/", null);
    3. Directory CurrentDirectory = null;
    4. foreach (string command in commands)
    5. {
    6. string[] cmdParts = command.Split(' ');
    7. if (cmdParts[0] == "$")
    8. {
    9. if (cmdParts[1] == "cd")
    10. {
    11. if (cmdParts[2] == "/")
    12. {
    13. CurrentDirectory = RootDirectory;
    14. }
    15. else if (cmdParts[2] == "..")
    16. {
    17. CurrentDirectory = CurrentDirectory.Parent;
    18. }
    19. else
    20. {
    21. CurrentDirectory = CurrentDirectory.Directories.FirstOrDefault(d => d.Name == cmdParts[2]);
    22. }
    23. }
    24. else
    25. {
    26. continue;
    27. }
    28. }
    29. else if (cmdParts[0] == "dir")
    30. {
    31. Directory tDir = new Directory(cmdParts[1], CurrentDirectory);
    32. CurrentDirectory.AddDirectory(tDir);
    33. }
    34. else
    35. {
    36. File tFile = new File(cmdParts[1], Int32.Parse(cmdParts[0]));
    37. CurrentDirectory.AddFile(tFile);
    38. }
    39. }
    40. Console.WriteLine($"Part 1: {RootDirectory.GetDirectorysSmallerThanSize(100000).Sum(x => x.TotalFileSize)}");
    41. int total = 70000000;
    42. int req = 30000000;
    43. int used = RootDirectory.TotalFileSize;
    44. int free = total - used;
    45. int need = req - free;
    46. Console.WriteLine($"Part 2: { RootDirectory.GetDirectorysSmallerThanSize(Int32.MaxValue).OrderBy(d => d.TotalFileSize).Where(d => d.TotalFileSize >= need).First().TotalFileSize }");
    47. public class Directory
    48. {
    49. public string Name { get; set; }
    50. public Directory Parent { get; set; }
    51. public List<Directory> Directories { get; private set; } = new List<Directory>();
    52. public int TotalFileSize => Files.Sum(f => f.Filesize) + Directories.Sum(d => d.TotalFileSize);
    53. public List<File> Files { get; set; } = new List<File>();
    54. public Directory(string name, Directory parent)
    55. {
    56. Name = name;
    57. Parent = parent;
    58. }
    59. public void AddDirectory(Directory newDir)
    60. {
    61. Directories.Add(newDir);
    62. }
    63. public void AddFile(File file)
    64. {
    65. Files.Add(file);
    66. }
    67. public List<Directory> GetDirectorysSmallerThanSize(int size)
    68. {
    69. List<Directory> result = new List<Directory>();
    70. foreach (var directory in Directories)
    71. {
    72. if(directory.TotalFileSize <= size)
    73. {
    74. result.Add(directory);
    75. }
    76. //else // Nice BAIT --- man muss alle Ordner beachten also auch Unter-Unter-Unter Ordner im Ordner. Lesen muss man richtig.
    77. //{
    78. // result.AddRange(directory.Value.GetDirectorysSmallerThanSize(size));
    79. //}
    80. result.AddRange(directory.GetDirectorysSmallerThanSize(size));
    81. }
    82. return result;
    83. }
    84. }
    85. public class File
    86. {
    87. public string Filename { get; set; } = "";
    88. public int Filesize { get; set; } = 0;
    89. public File(string fileName, int size)
    90. {
    91. Filename = fileName;
    92. Filesize = size;
    93. }
    94. }
    Grüße , xChRoNiKx

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

    Spoiler anzeigen

    C#-Quellcode

    1. namespace SevenA;
    2. public class Program
    3. {
    4. static void Main(string[] args)
    5. {
    6. IEnumerable<string> data = System.IO.File.ReadAllLines("input.txt");
    7. FilesystemU fileSystem = new();
    8. for (int i = 0; i < data.Count(); i++)
    9. {
    10. IEnumerable<string> tokens = data.ElementAt(i).Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
    11. if (tokens.ElementAt(0) == "$" && tokens.ElementAt(1) == "cd")
    12. fileSystem.Execute(tokens);
    13. if (tokens.ElementAt(0) == "$" && tokens.ElementAt(1) == "ls")
    14. {
    15. List<string> listing = new();
    16. while (true)
    17. {
    18. i++;
    19. if (i >= data.Count()) break;
    20. if (data.ElementAt(i).StartsWith("$"))
    21. {
    22. i--;
    23. break;
    24. }
    25. listing.Add(data.ElementAt(i));
    26. }
    27. fileSystem.ExecuteListing(listing);
    28. }
    29. }
    30. //Für Part1
    31. Console.WriteLine(fileSystem.Directories.Where(x => x.TotalSize <= 100000).Sum(x => x.TotalSize));
    32. //Für Part2
    33. long totalSpace = 70000000;
    34. long spaceNeeded = 30000000;
    35. long unused = totalSpace - fileSystem.Directories[0].TotalSize;
    36. long needed = spaceNeeded - unused;
    37. var candidates = fileSystem.Directories.Where(x => x.TotalSize >= needed);
    38. candidates = candidates.OrderBy(x => x.TotalSize);
    39. Console.WriteLine($"{candidates.ElementAt(0).Name} - {candidates.ElementAt(0).TotalSize}");
    40. }
    41. }
    42. class FilesystemU
    43. {
    44. public List<FileU> Files { get; set; } = new();
    45. public List<DirectoryU> Directories { get; set; } = new();
    46. public List<DirectoryU> CurrentPath { get; set; } = new();
    47. public void Execute(IEnumerable<string> command)
    48. {
    49. if (command.ElementAt(0) == "$")
    50. {
    51. if (command.ElementAt(1) == "cd")
    52. {
    53. if (command.ElementAt(2) != "..")
    54. {
    55. DirectoryU dir = CheckDirectory(command.ElementAt(2), this.CurrentPath.Count > 0 ? this.CurrentPath.Last() : null);
    56. if (!this.Directories.Contains(dir))
    57. this.Directories.Add(dir);
    58. this.CurrentPath.Add(dir);
    59. }
    60. if (command.ElementAt(2) == "..")
    61. {
    62. this.CurrentPath.RemoveAt(this.CurrentPath.Count - 1);
    63. }
    64. }
    65. }
    66. }
    67. public void ExecuteListing(IEnumerable<string> data)
    68. {
    69. for (int i = 0; i < data.Count(); i++)
    70. {
    71. IEnumerable<string> tokens = data.ElementAt(i).Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
    72. if (tokens.ElementAt(0) == "dir")
    73. {
    74. var dir = CheckDirectory(tokens.ElementAt(1), this.CurrentPath.Last());
    75. if (!this.Directories.Contains(dir))
    76. this.Directories.Add(dir);
    77. this.CurrentPath.Last().Directories.Add(dir);
    78. }
    79. else
    80. {
    81. FileU file = new();
    82. file.Name = tokens.ElementAt(1);
    83. file.Size = long.Parse(tokens.ElementAt(0));
    84. file.Parent = this.CurrentPath.Last();
    85. this.Files.Add(file);
    86. this.CurrentPath.Last().Files.Add(file);
    87. }
    88. }
    89. }
    90. private DirectoryU CheckDirectory(string name, DirectoryU parent)
    91. {
    92. DirectoryU dir = null;
    93. if (this.CurrentPath.Count() > 0)
    94. dir = this.CurrentPath.Last().Directories.Where(x => x.Name == name).FirstOrDefault();
    95. if (dir == null)
    96. {
    97. dir = new DirectoryU()
    98. {
    99. Name = name,
    100. Parent = parent
    101. };
    102. }
    103. return dir;
    104. }
    105. }
    106. class DirectoryU
    107. {
    108. public string Name { get; set; }
    109. public DirectoryU Parent { get; set; }
    110. public List<DirectoryU> Directories { get; set; } = new();
    111. public List<FileU> Files { get; set; } = new();
    112. public long Size { get => this.Files.Sum(x => x.Size); set => this.Size = value; }
    113. public long TotalSize { get => CalculateTotalSize(); set => this.TotalSize = value; }
    114. private long CalculateTotalSize()
    115. {
    116. List<DirectoryU> tmp = new(this.Directories);
    117. long result = 0;
    118. while (tmp.Count > 0)
    119. {
    120. List<DirectoryU> tmp1 = new();
    121. for (int i = 0; i < tmp.Count; i++)
    122. {
    123. tmp1.AddRange(tmp[i].Directories);
    124. result += tmp[i].Size;
    125. }
    126. tmp.Clear();
    127. tmp.AddRange(tmp1);
    128. }
    129. return result + this.Size;
    130. }
    131. }
    132. class FileU
    133. {
    134. public string Name { get; set; }
    135. public DirectoryU Parent { get; set; }
    136. public long Size { get; set; }
    137. }

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

    C#-Quellcode

    1. public static class AoC_D8
    2. {
    3. public static TreeGrid MainGrid { get; } = new TreeGrid();
    4. public static int VisibleTrees { get; private set; }
    5. public static int HighestScenicScore { get; private set; }
    6. public static void ReadInputAndCalculate()
    7. {
    8. using StreamReader streamReader = new StreamReader("AoC_8_input.txt");
    9. do
    10. {
    11. string line = streamReader.ReadLine();
    12. if (string.IsNullOrWhiteSpace(line))
    13. continue;
    14. MainGrid.AddRowFromLine(line);
    15. } while (!streamReader.EndOfStream);
    16. CalculateVisibleTrees();
    17. CalculateScenicScores();
    18. HighestScenicScore = MainGrid.AllTrees.Max(x => x.ScenicScore);
    19. }
    20. private static void CalculateVisibleTrees()
    21. {
    22. foreach (var rows in MainGrid.Rows)
    23. foreach (var tree in rows.Trees)
    24. if (tree.CalculateTreeVisibility())
    25. VisibleTrees++;
    26. }
    27. private static void CalculateScenicScores()
    28. {
    29. foreach (var rows in MainGrid.Rows)
    30. foreach (var tree in rows.Trees)
    31. tree.CalculateScore();
    32. }
    33. }
    34. public class Tree
    35. {
    36. public int Size { get; set; }
    37. public int Row { get; set; }
    38. public int Column { get; set; }
    39. public TreeGrid Grid { get; set; }
    40. public int ScenicScore { get; set; }
    41. public void CalculateScore()
    42. {
    43. if (Row == 0 || Row == 98 || Column == 0 || Column == 98)
    44. ScenicScore = 0;
    45. ScenicScore = CalculateScoreAbove() *
    46. CalculateScoreBelow() *
    47. CalculateScoreLeft() *
    48. CalculateScoreRight();
    49. }
    50. public bool CalculateTreeVisibility()
    51. {
    52. if (Row == 0 || Row == 98 || Column == 0 || Column == 98)
    53. return true;
    54. return IsTreeVisibleFromAbove() ||
    55. IsTreeVisibleFromBelow() ||
    56. IsTreeVisibleFromLeft() ||
    57. IsTreeVisibleFromRight();
    58. }
    59. private int CalculateScoreLeft()
    60. {
    61. for (int searchColumn = Column - 1; searchColumn >= 0; searchColumn--)
    62. {
    63. int searchSize = Grid[Row][searchColumn].Size;
    64. if (searchSize >= Size)
    65. return Column - searchColumn;
    66. }
    67. return Column;
    68. }
    69. private int CalculateScoreRight()
    70. {
    71. for (int searchColumn = Column + 1; searchColumn < 99; searchColumn++)
    72. {
    73. int searchSize = Grid[Row][searchColumn].Size;
    74. if (searchSize >= Size)
    75. return searchColumn - Column;
    76. }
    77. return 98 - Column;
    78. }
    79. private int CalculateScoreAbove()
    80. {
    81. for (int searchRow = Row - 1; searchRow >= 0; searchRow--)
    82. {
    83. int searchSize = Grid[searchRow][Column].Size;
    84. if (searchSize >= Size)
    85. return Row - searchRow;
    86. }
    87. return Row;
    88. }
    89. private int CalculateScoreBelow()
    90. {
    91. for (int searchRow = Row + 1; searchRow < 99; searchRow++)
    92. {
    93. int searchSize = Grid[searchRow][Column].Size;
    94. if (searchSize >= Size)
    95. return searchRow - Row;
    96. }
    97. return 98 - Row;
    98. }
    99. private bool IsTreeVisibleFromLeft()
    100. {
    101. for (int searchColumn = Column - 1; searchColumn >= 0; searchColumn--)
    102. {
    103. int searchSize = Grid[Row][searchColumn].Size;
    104. if (searchSize >= Size)
    105. return false;
    106. }
    107. return true;
    108. }
    109. private bool IsTreeVisibleFromRight()
    110. {
    111. for (int searchColumn = Column + 1; searchColumn < 99; searchColumn++)
    112. {
    113. int searchSize = Grid[Row][searchColumn].Size;
    114. if (searchSize >= Size)
    115. return false;
    116. }
    117. return true;
    118. }
    119. private bool IsTreeVisibleFromAbove()
    120. {
    121. for (int searchRow = Row - 1; searchRow >= 0; searchRow--)
    122. {
    123. int searchSize = Grid[searchRow][Column].Size;
    124. if (searchSize >= Size)
    125. return false;
    126. }
    127. return true;
    128. }
    129. private bool IsTreeVisibleFromBelow()
    130. {
    131. for (int searchRow = Row + 1; searchRow < 99; searchRow++)
    132. {
    133. int searchSize = Grid[searchRow][Column].Size;
    134. if (searchSize >= Size)
    135. return false;
    136. }
    137. return true;
    138. }
    139. }
    140. public class TreeGrid
    141. {
    142. private int rowNo = 0;
    143. public List<TreeRow> Rows { get; } = new List<TreeRow>();
    144. public List<Tree> AllTrees { get; } = new List<Tree>();
    145. public TreeRow this[int i] => Rows[i];
    146. public void AddRowFromLine(string line)
    147. {
    148. TreeRow current = new TreeRow(rowNo);
    149. for (int column = 0; column < line.Length; column++)
    150. {
    151. current.Trees.Add(new Tree
    152. {
    153. Column = column,
    154. Row = rowNo,
    155. Grid = this,
    156. Size = int.Parse(line[column].ToString())
    157. });
    158. AllTrees.Add(current.Trees.Last());
    159. }
    160. Rows.Add(current);
    161. rowNo++;
    162. }
    163. }
    164. public class TreeRow
    165. {
    166. public int RowNo { get; }
    167. public List<Tree> Trees { get; } = new List<Tree>();
    168. public Tree this[int i] => Trees[i];
    169. public TreeRow(int rowNo)
    170. { RowNo = rowNo; }
    171. }


    Zudem hab ich jetzt auch ein GitHub Repo dafür angelegt:
    github.com/EaranMaleasi/AoC_Projects_2022
    Tag 8 C# - Das geht noch schöner allerdings heute keine Lust mehr :D
    Part 1 und 2
    Spoiler anzeigen

    C#-Quellcode

    1. string[] lines = File.ReadAllLines("Input.txt");
    2. int rows = lines.Length;
    3. int cols = lines[0].ToCharArray().Count();
    4. int[,] field = new int[rows,cols];
    5. List<int> scenicScores = new List<int>();
    6. int rowCount = 0;
    7. int colCount = 0;
    8. int visibleTrees = 0;
    9. foreach (string line in lines)
    10. {
    11. colCount = 0;
    12. char[] chars = line.ToCharArray();
    13. foreach (char c in chars)
    14. {
    15. field[rowCount,colCount] = Int32.Parse(c.ToString());
    16. colCount++;
    17. }
    18. rowCount++;
    19. }
    20. for (int row = 0; row < rows; row++)
    21. {
    22. for (int col = 0; col < cols; col++)
    23. {
    24. scenicScores.Add(calculateTopScenicScore(row, col) * calculateBottomScenicScore(row, col) * calculateLeftScenicScore(row, col) * calculateRightScenicScore(row, col));
    25. if (IsVisible(row, col)) visibleTrees++;
    26. }
    27. }
    28. Console.WriteLine($"Part 1: {visibleTrees}");
    29. Console.WriteLine($"Part 2: {scenicScores.Max()}");
    30. bool IsVisible(int x, int y)
    31. {
    32. if (x == 0 || y == 0 || x == rows - 1 || y == cols - 1) return true;
    33. if (checkLeft(x, y)) return true;
    34. if (checkRight(x, y)) return true;
    35. if (checkTop(x, y)) return true;
    36. if (checkBottom(x, y)) return true;
    37. return false;
    38. }
    39. int calculateLeftScenicScore(int x, int y)
    40. {
    41. int height = field[x, y];
    42. int score = 0;
    43. for (int i = y - 1; i >= 0; i--)
    44. {
    45. int curHeight = field[x, i];
    46. if (curHeight >= height) return score +1;
    47. score++;
    48. }
    49. return score;
    50. }
    51. int calculateRightScenicScore(int x, int y)
    52. {
    53. int height = field[x, y];
    54. int score = 0;
    55. for (int i = y + 1; i < cols; i++)
    56. {
    57. int curHeight = field[x, i];
    58. if (curHeight >= height) return score + 1;
    59. score++;
    60. }
    61. return score;
    62. }
    63. int calculateTopScenicScore(int x, int y)
    64. {
    65. int height = field[x, y];
    66. int score = 0;
    67. for (int i = x - 1; i >= 0; i--)
    68. {
    69. int curHeight = field[i, y];
    70. if (curHeight >= height) return score + 1;
    71. score++;
    72. }
    73. return score;
    74. }
    75. int calculateBottomScenicScore(int x, int y)
    76. {
    77. int height = field[x, y];
    78. int score = 0;
    79. for (int i = x + 1; i < cols; i++)
    80. {
    81. int curHeight = field[i, y];
    82. if (curHeight >= height) return score + 1;
    83. score++;
    84. }
    85. return score;
    86. }
    87. bool checkLeft(int x, int y)
    88. {
    89. int height = field[x,y];
    90. for (int i = y -1; i >= 0; i--)
    91. {
    92. int curHeight = field[x, i];
    93. if (curHeight >= height) return false;
    94. }
    95. return true;
    96. }
    97. bool checkRight(int x, int y)
    98. {
    99. int height = field[x, y];
    100. for (int i = y + 1; i < cols; i++)
    101. {
    102. int curHeight = field[x, i];
    103. if (curHeight >= height) return false;
    104. }
    105. return true;
    106. }
    107. bool checkTop(int x, int y)
    108. {
    109. int height = field[x, y];
    110. for (int i = x - 1; i >= 0; i--)
    111. {
    112. int curHeight = field[i, y];
    113. if (curHeight >= height) return false;
    114. }
    115. return true;
    116. }
    117. bool checkBottom(int x, int y)
    118. {
    119. int height = field[x, y];
    120. for (int i = x + 1; i < cols; i++)
    121. {
    122. int curHeight = field[i, y];
    123. if (curHeight >= height) return false;
    124. }
    125. return true;
    126. }
    Grüße , xChRoNiKx

    Nützliche Links:
    Visual Studio Empfohlene Einstellungen | Try-Catch heißes Eisen
    Tag 8
    Teil 1 und 2 C#
    (wie ich das Debuggen mit Indizes etc. dislike <X )
    Spoiler anzeigen

    C#-Quellcode

    1. using System.Linq;
    2. using System.Text.RegularExpressions;
    3. var Lines = File.ReadAllLines("CodeAdvent_8.txt");
    4. var YMax = Lines.Length;
    5. var XMax = Lines[0].Length;
    6. List <List<int>> Rows = new();
    7. List <List<int>> Columns = new();
    8. List<Tree> Trees = new();
    9. foreach (var line in Lines)
    10. {
    11. var nrs = Regex.Matches(line, @"\d").ToList();
    12. List<int> Row= new ();
    13. foreach (var nr in nrs)
    14. {
    15. Row.Add(int.Parse(nr.Value));
    16. }
    17. Rows.Add(Row);
    18. }
    19. var TreeCount = 0;
    20. for (int x = 0; x < XMax; x++)
    21. {
    22. List<int> Column= new();
    23. for (int y = 0; y < YMax; y++)
    24. {
    25. TreeCount++;
    26. Column.Add(Rows[y].ElementAt(x));
    27. Trees.Add(new(y, x, Rows[x].ElementAt(y), TreeCount));
    28. }
    29. Columns.Add(Column);
    30. }
    31. foreach (var tree in Trees)
    32. {
    33. tree.SetIsVisible(Rows[tree.PosY], Columns[tree.PosX]);
    34. tree.SetScenicScore(Rows[tree.PosY], Columns[tree.PosX]);
    35. }
    36. Console.WriteLine($"Visible Trees: {Trees.Where(x => x.IsVisible).Count()}");
    37. Console.WriteLine($"MaxScenicScore: {Trees.MaxBy(x => x.ScenicScore).ScenicScore}");
    38. class Tree
    39. {
    40. public Tree(int posX, int posY, int height, int id)
    41. {
    42. PosX = posX;
    43. PosY = posY;
    44. Height = height;
    45. Id= id;
    46. }
    47. public int Id { get; set; } = 0;
    48. public int Height = 0;
    49. public int PosX { get; set; } = 0;
    50. public int PosY { get; set; } = 0;
    51. public int ScenicScore { get; set; } = 0;
    52. public bool XVisible { get; set; } = false;
    53. public bool YVisible { get; set; } = false;
    54. public bool IsVisible { get { return XVisible || YVisible; } }
    55. public void SetScenicScore(List<int> row, List<int> column)
    56. {
    57. List<int> rLeft = row.GetRange(0, PosX);
    58. List<int> rRight = row.GetRange(PosX + 1, row.Count - PosX - 1);
    59. rLeft.Reverse();
    60. int scoreLeftR = 0;
    61. int scoreRightR = 0;
    62. if (rLeft.Count == 0)
    63. {
    64. scoreLeftR = 0;
    65. }
    66. else
    67. {
    68. var keepLooking = true;
    69. foreach (var t in rLeft)
    70. {
    71. if (keepLooking)
    72. {
    73. scoreLeftR++;
    74. }
    75. if (t >= Height)
    76. {
    77. keepLooking = false;
    78. }
    79. }
    80. }
    81. if (rRight.Count == 0)
    82. {
    83. scoreRightR = 0;
    84. }
    85. else
    86. {
    87. var keepLooking = true;
    88. foreach (var t in rRight)
    89. {
    90. if (keepLooking)
    91. {
    92. scoreRightR++;
    93. }
    94. if (t >= Height)
    95. {
    96. keepLooking = false;
    97. }
    98. }
    99. }
    100. var cLeft = column.GetRange(0, PosY);
    101. var cRight = column.GetRange(PosY + 1, column.Count - PosY - 1);
    102. cLeft.Reverse();
    103. int scoreLeftC = 0;
    104. int scoreRightC = 0;
    105. if (cLeft.Count == 0)
    106. {
    107. scoreLeftC = 0;
    108. }
    109. else
    110. {
    111. var keepLooking = true;
    112. foreach (var t in cLeft)
    113. {
    114. if (keepLooking)
    115. {
    116. scoreLeftC++;
    117. }
    118. if (t >= Height)
    119. {
    120. keepLooking = false;
    121. }
    122. }
    123. }
    124. if (cRight.Count == 0)
    125. {
    126. scoreRightC = 0;
    127. }
    128. else
    129. {
    130. var keepLooking = true;
    131. foreach (var t in cRight)
    132. {
    133. if (keepLooking)
    134. {
    135. scoreRightC++;
    136. }
    137. if (t >= Height)
    138. {
    139. keepLooking = false;
    140. }
    141. }
    142. }
    143. ScenicScore = scoreRightC * scoreLeftC * scoreRightR * scoreLeftR;
    144. }
    145. public void SetIsVisible(List<int> row, List<int> column)
    146. {
    147. var rLeft = row.GetRange(0, PosX);
    148. var rRight = row.GetRange(PosX+1, row.Count - PosX - 1);
    149. bool visibleFromLeft = false;
    150. bool visibleFromRight = false;
    151. if (rLeft.Count == 0)
    152. {
    153. visibleFromLeft = true;
    154. }
    155. else
    156. {
    157. var res = rLeft.Max() ;
    158. visibleFromLeft = res < Height;
    159. }
    160. if (rRight.Count == 0)
    161. {
    162. visibleFromRight = true;
    163. }
    164. else
    165. {
    166. var res = rRight.Max();
    167. visibleFromRight = res < Height;
    168. }
    169. XVisible = visibleFromLeft || visibleFromRight;
    170. var cLeft = column.GetRange(0, PosY);
    171. var cRight = column.GetRange(PosY + 1, column.Count - PosY - 1);
    172. bool visibleFromLeftc = false;
    173. bool visibleFromRightc = false;
    174. if (cLeft.Count == 0)
    175. {
    176. visibleFromLeftc = true;
    177. }
    178. else
    179. {
    180. var res = cLeft.Max();
    181. visibleFromLeftc = res < Height;
    182. }
    183. if (cRight.Count == 0)
    184. {
    185. visibleFromRightc = true;
    186. }
    187. else
    188. {
    189. var res = cRight.Max();
    190. visibleFromRightc = res < Height;
    191. }
    192. YVisible = visibleFromLeftc || visibleFromRightc;
    193. }
    194. }
    codewars.com Rank: 4 kyu
    Tag 7 war irgendwie nervig. Lag vielleicht auch an einem generell bescheidenen Tag gestern :D
    Part 1
    Spoiler anzeigen

    C#-Quellcode

    1. using System.Text.RegularExpressions;
    2. using StreamReader sr = new(File.OpenRead(@"input.txt"));
    3. const int threshold = 100_000;
    4. Regex commandRegex = new("(\\$).(\\w+).?(\\/|\\w+|\\.\\.)*", RegexOptions.Compiled);
    5. Regex listingRegex = new("(dir|\\d+).(\\w+)", RegexOptions.Compiled);
    6. bool listMode = false;
    7. D rootDir = new() { Name = "/" };
    8. D workingDir = new();
    9. while (!sr.EndOfStream)
    10. {
    11. var line = sr.ReadLine()!;
    12. if (listMode)
    13. {
    14. if (listingRegex.IsMatch(line))
    15. {
    16. foreach (Match m in listingRegex.Matches(line))
    17. {
    18. if (m.Groups[1].Value == "dir")
    19. {
    20. workingDir.Subdirs.Add(new() { Name = m.Groups[2].Value });
    21. }
    22. else
    23. {
    24. workingDir.Files.Add(new() { Name = m.Groups[2].Value, Size = int.Parse(m.Groups[1].Value) });
    25. }
    26. }
    27. }
    28. }
    29. if (commandRegex.IsMatch(line))
    30. {
    31. foreach (Match m in commandRegex.Matches(line))
    32. {
    33. switch (m.Groups[2].Value)
    34. {
    35. case "cd":
    36. listMode = false;
    37. D currentDir = workingDir;
    38. workingDir = m.Groups[3].Value switch
    39. {
    40. "/" => rootDir,
    41. ".." => workingDir!.Parent,
    42. _ => workingDir.Subdirs.First(d => d.Name!.Equals(m.Groups[3].Value))
    43. };
    44. if (workingDir!.Parent is null)
    45. {
    46. workingDir!.Parent = currentDir;
    47. }
    48. break;
    49. case "ls":
    50. listMode = true;
    51. break;
    52. }
    53. }
    54. }
    55. }
    56. List<int> sizes = new();
    57. foreach (var dir in rootDir.Subdirs)
    58. {
    59. TotalSizeD(dir);
    60. }
    61. Console.WriteLine(sizes.Sum());
    62. int TotalSizeD(D dir)
    63. {
    64. int total = 0;
    65. if (dir.Subdirs.Count > 0)
    66. {
    67. for (int i = 0; i < dir.Subdirs.Count; ++i)
    68. {
    69. total += TotalSizeD(dir.Subdirs[i]);
    70. }
    71. }
    72. total += dir.Size;
    73. if (total <= threshold)
    74. {
    75. sizes.Add(total);
    76. }
    77. return total;
    78. }
    79. class D
    80. {
    81. public string? Name { get; set; }
    82. public int Size => Files.Sum(f => f.Size);
    83. public List<F> Files { get; init; } = new();
    84. public List<D> Subdirs { get; set; } = new();
    85. public D? Parent { get; set; }
    86. }
    87. struct F
    88. {
    89. public string Name;
    90. public int Size;
    91. }


    Part 2
    Spoiler anzeigen

    C#-Quellcode

    1. using System.Text.RegularExpressions;
    2. using StreamReader sr = new(File.OpenRead(@"input.txt"));
    3. const int maxAvailable = 70_000_000;
    4. const int minAvailableForUpdate = 30_000_000;
    5. Regex commandRegex = new("(\\$).(\\w+).?(\\/|\\w+|\\.\\.)*", RegexOptions.Compiled);
    6. Regex listingRegex = new("(dir|\\d+).(\\w+)", RegexOptions.Compiled);
    7. bool listMode = false;
    8. D rootDir = new() { Name = "/" };
    9. D workingDir = new();
    10. while (!sr.EndOfStream)
    11. {
    12. var line = sr.ReadLine()!;
    13. if (listMode)
    14. {
    15. if (listingRegex.IsMatch(line))
    16. {
    17. foreach (Match m in listingRegex.Matches(line))
    18. {
    19. if (m.Groups[1].Value == "dir")
    20. {
    21. workingDir.Subdirs.Add(new() { Name = m.Groups[2].Value });
    22. }
    23. else
    24. {
    25. workingDir.Files.Add(new() { Name = m.Groups[2].Value, Size = int.Parse(m.Groups[1].Value) });
    26. }
    27. }
    28. }
    29. }
    30. if (commandRegex.IsMatch(line))
    31. {
    32. foreach (Match m in commandRegex.Matches(line))
    33. {
    34. switch (m.Groups[2].Value)
    35. {
    36. case "cd":
    37. listMode = false;
    38. D currentDir = workingDir;
    39. workingDir = m.Groups[3].Value switch
    40. {
    41. "/" => rootDir,
    42. ".." => workingDir!.Parent,
    43. _ => workingDir.Subdirs.First(d => d.Name!.Equals(m.Groups[3].Value))
    44. };
    45. if (workingDir!.Parent is null)
    46. {
    47. workingDir!.Parent = currentDir;
    48. }
    49. break;
    50. case "ls":
    51. listMode = true;
    52. break;
    53. }
    54. }
    55. }
    56. }
    57. List<int> sizes = new();
    58. int total = rootDir.Size;
    59. foreach (var dir in rootDir.Subdirs)
    60. {
    61. total += TotalSize(dir);
    62. }
    63. int freeSpace = maxAvailable - total;
    64. foreach (var dir in rootDir.Subdirs)
    65. {
    66. FindDForEnoughSpace(dir);
    67. }
    68. Console.WriteLine(sizes.Min());
    69. int TotalSize(D dir)
    70. {
    71. int total = dir.Size;
    72. if (dir.Subdirs.Count > 0)
    73. {
    74. for (int i = 0; i < dir.Subdirs.Count; ++i)
    75. {
    76. total += TotalSize(dir.Subdirs[i]);
    77. }
    78. }
    79. return total;
    80. }
    81. int FindDForEnoughSpace(D dir)
    82. {
    83. int size = dir.Size;
    84. if (dir.Subdirs.Count > 0)
    85. {
    86. for (int i = 0; i < dir.Subdirs.Count; ++i)
    87. {
    88. size += FindDForEnoughSpace(dir.Subdirs[i]);
    89. }
    90. }
    91. if ((size + freeSpace) >= minAvailableForUpdate)
    92. {
    93. sizes.Add(size);
    94. }
    95. return size;
    96. }
    97. class D
    98. {
    99. public string? Name { get; set; }
    100. public int Size => Files.Sum(f => f.Size);
    101. public List<F> Files { get; init; } = new();
    102. public List<D> Subdirs { get; set; } = new();
    103. public D? Parent { get; set; }
    104. }
    105. struct F
    106. {
    107. public string Name;
    108. public int Size;
    109. }


    Tag 8
    Part 1
    Spoiler anzeigen

    C#-Quellcode

    1. using StreamReader sr = new(File.OpenRead(@"input.txt"));
    2. HashSet<P> points = new();
    3. int currentRow = 0;
    4. int maxCols = 0;
    5. int maxRows = 0;
    6. int visibleTrees = 0;
    7. while (!sr.EndOfStream)
    8. {
    9. var lineSpan = sr.ReadLine().AsSpan();
    10. if (maxCols == 0)
    11. {
    12. maxCols = lineSpan.Length - 1;
    13. }
    14. for (int i = 0; i < lineSpan.Length; ++i)
    15. {
    16. points.Add(new() { X = i, Y = currentRow, Height = int.Parse(lineSpan.Slice(i, 1)) });
    17. }
    18. ++currentRow;
    19. }
    20. sr.Close();
    21. maxRows = currentRow - 1;
    22. int[,] matrix = new int[99, 99];
    23. foreach (P p in points)
    24. {
    25. matrix[p.X, p.Y] = p.Height;
    26. }
    27. for (int i = 0; i <= maxRows; ++i)
    28. {
    29. for (int j = 0; j <= maxCols; ++j)
    30. {
    31. if ((i == 0) || (j == 0) || (i == maxRows) || (j == maxCols))
    32. {
    33. ++visibleTrees;
    34. }
    35. else
    36. {
    37. int h = matrix[j, i];
    38. if (((i > 0) && CheckIfVisible(h, j, i - 1, points.Where(s => s.Y < i && s.X == j).Max(s => s.Height))) ||
    39. ((j > 0) && CheckIfVisible(h, j - 1, i, points.Where(s => s.Y == i && s.X < j).Max(s => s.Height))) ||
    40. ((i < maxRows) && CheckIfVisible(h, j, i + 1, points.Where(s => s.Y > i && s.X == j).Max(s => s.Height))) ||
    41. ((j < maxCols) && CheckIfVisible(h, j + 1, i, points.Where(s => s.Y == i && s.X > j).Max(s => s.Height))))
    42. {
    43. ++visibleTrees;
    44. }
    45. }
    46. }
    47. }
    48. Console.WriteLine(visibleTrees);
    49. bool CheckIfVisible(int h, int x, int y, int heighest)
    50. {
    51. return (h > matrix[x, y]) && (h > heighest);
    52. }
    53. struct P
    54. {
    55. public int X;
    56. public int Y;
    57. public int Height;
    58. }


    Part 2
    Spoiler anzeigen

    C#-Quellcode

    1. using StreamReader sr = new(File.OpenRead(@"input.txt"));
    2. HashSet<P> points = new();
    3. int currentRow = 0;
    4. int maxCols = 0;
    5. int maxRows = 0;
    6. while (!sr.EndOfStream)
    7. {
    8. var lineSpan = sr.ReadLine().AsSpan();
    9. if (maxCols == 0)
    10. {
    11. maxCols = lineSpan.Length - 1;
    12. }
    13. for (int i = 0; i < lineSpan.Length; ++i)
    14. {
    15. points.Add(new() { X = i, Y = currentRow, Height = int.Parse(lineSpan.Slice(i, 1)) });
    16. }
    17. ++currentRow;
    18. }
    19. sr.Close();
    20. maxRows = currentRow - 1;
    21. int maxScore = 0;
    22. int[,] matrix = new int[99, 99];
    23. foreach (P p in points)
    24. {
    25. matrix[p.X, p.Y] = p.Height;
    26. }
    27. for (int i = 0; i <= maxRows; ++i)
    28. {
    29. for (int j = 0; j <= maxCols; ++j)
    30. {
    31. int score = CalculateScore(matrix[j, i], j, i);
    32. maxScore = score > maxScore ? score : maxScore;
    33. }
    34. }
    35. Console.WriteLine(maxScore);
    36. int CalculateScore(int h, int x, int y)
    37. {
    38. int score = 1;
    39. if (x > 0)
    40. {
    41. score *= TreeCountLeft(h, x, y);
    42. }
    43. score *= TreeCountRight(h, x, y);
    44. score *= TreeCountUp(h, x, y);
    45. if (y > 0)
    46. {
    47. score *= TreeCountDown(h, x, y);
    48. }
    49. return score;
    50. }
    51. int TreeCountLeft(int h, int x, int y)
    52. {
    53. int treeCount = 0;
    54. for (int i = x - 1; i >= 0; --i)
    55. {
    56. treeCount++;
    57. if (h <= matrix[i, y])
    58. {
    59. break;
    60. }
    61. }
    62. return treeCount;
    63. }
    64. int TreeCountRight(int h, int x, int y)
    65. {
    66. int treeCount = 0;
    67. for (int i = x + 1; i <= maxCols; ++i)
    68. {
    69. treeCount++;
    70. if (h <= matrix[i, y])
    71. {
    72. break;
    73. }
    74. }
    75. return treeCount;
    76. }
    77. int TreeCountDown(int h, int x, int y)
    78. {
    79. int treeCount = 0;
    80. for (int i = y + 1; i <= maxRows; ++i)
    81. {
    82. treeCount++;
    83. if (h <= matrix[x, i])
    84. {
    85. break;
    86. }
    87. }
    88. return treeCount;
    89. }
    90. int TreeCountUp(int h, int x, int y)
    91. {
    92. int treeCount = 0;
    93. for (int i = y - 1; i >= 0; --i)
    94. {
    95. treeCount++;
    96. if (h <= matrix[x, i])
    97. {
    98. break;
    99. }
    100. }
    101. return treeCount;
    102. }
    103. struct P
    104. {
    105. public int X;
    106. public int Y;
    107. public int Height;
    108. }

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

    Tag 8 / PowerShell

    Spoiler anzeigen

    Quellcode

    1. # https://adventofcode.com/2022/day/8
    2. # Build input array
    3. [System.Collections.ArrayList]$Row = @()
    4. foreach ($Line in Get-Content -Path $PSScriptRoot\day08_input.txt) {
    5. [System.Collections.ArrayList]$Column = @()
    6. foreach ($Char in $Line.ToCharArray()) {
    7. [void]$Column.Add([int]$Char.ToString())
    8. }
    9. [void]$Row.Add($Column)
    10. }
    11. # Ignore borders, so we can ignore the first and last row and column
    12. # when iterating over the array
    13. $VisibleTrees = ($Row.Count * 2) + ($Row[0].Count * 2) - 4
    14. $TreeScenicScore = 0
    15. # Go through each row
    16. for ($i = 1; $i -lt $Row.Count - 1; $i++) {
    17. # Go through each column
    18. for ($y = 1; $y -lt $Row[$i].Count - 1; $y++) {
    19. $CurrentTree = $Row[$i][$y]
    20. Write-Host "Current tree is [$i,$y] with value $CurrentTree"
    21. # Left
    22. $LeftVisible = $true
    23. $LeftCount = 0
    24. foreach($l in $Row[$i][($y - 1)..0]) {
    25. $LeftCount++
    26. if ($l -ge $CurrentTree) {
    27. $LeftVisible = $false
    28. break
    29. }
    30. }
    31. # Right
    32. $RightVisible = $true
    33. $RightCount = 0
    34. foreach($r in $Row[$i][($y + 1)..$($Row[$y].Count)]) {
    35. $RightCount++
    36. if ($r -ge $CurrentTree) {
    37. $RightVisible = $false
    38. break
    39. }
    40. }
    41. # Top
    42. $TopVisible = $true
    43. $TopCount = 0
    44. foreach($t in $Row[($i - 1)..0]) {
    45. $TopCount++
    46. if($($t[$y]) -ge $CurrentTree) {
    47. $TopVisible = $false
    48. break
    49. }
    50. }
    51. # Bottom
    52. $BotVisible = $true
    53. $BotCount = 0
    54. foreach($b in $Row[($i + 1)..$($Row[$i].Count)]) {
    55. $BotCount++
    56. if($($b[$y]) -ge $CurrentTree) {
    57. $BotVisible = $false
    58. break
    59. }
    60. }
    61. # Check if tree is visible
    62. if ($LeftVisible -or $TopVisible -or $RightVisible -or $BotVisible) {
    63. $VisibleTrees++
    64. }
    65. # Check scenic score
    66. $CurrentTreeScenicScore = $TopCount * $LeftCount * $BotCount * $RightCount
    67. if ($CurrentTreeScenicScore -gt $TreeScenicScore) {
    68. $TreeScenicScore = $CurrentTreeScenicScore
    69. }
    70. }
    71. }
    72. Write-Host "Part 1: $VisibleTrees"
    73. Write-Host "Part 2: $TreeScenicScore"
    NETworkManager - A powerful tool for managing networks and troubleshoot network problems!
    Day 5 to Day 9 and only the first task in each case.

    Day05

    C#-Quellcode

    1. private static void Part01()
    2. {
    3. [MethodImpl(MethodImplOptions.AggressiveInlining)]
    4. static void move_operations(Stack<char>[] stack, int[] operation)
    5. {
    6. for (var i = 0; i < operation[0]; i++)
    7. stack[operation[2] - 1].Push(stack[operation[1] - 1].Pop());
    8. }
    9. var stacks = SourceStacks();
    10. var operations = Operations();
    11. foreach (var op in operations)
    12. move_operations(stacks, op);
    13. Console.Write("message = ");
    14. Array.ForEach(stacks, stc => Console.Write(stc.First()));
    15. Console.WriteLine();
    16. Console.ReadLine();
    17. }

    Sources

    C#-Quellcode

    1. private static Stack<char>[] SourceStacks()
    2. {
    3. return Source()
    4. .Select(s => new Stack<char>(s.ToCharArray()))
    5. .ToArray();
    6. }
    7. private static string[] Source()
    8. {
    9. return new string[]
    10. {
    11. "ZN","MCD","P"
    12. };
    13. }
    14. private static int[][] Operations()
    15. {
    16. return new int[][]
    17. {
    18. new []{ 1,2,1},
    19. new []{ 3,1,3},
    20. new []{ 2,2,1},
    21. new []{ 1,1,2}
    22. };
    23. }

    Day06

    C#-Quellcode

    1. private static void Part01()
    2. {
    3. [MethodImpl(MethodImplOptions.AggressiveInlining)]
    4. static bool has_dublicate(string src, int start, int sequencelength)
    5. => sequencelength != src.Substring(start, sequencelength).Distinct().Count();
    6. var sequencelength = 4;
    7. var result = new List<int>();
    8. Array.ForEach(Sources(), src =>
    9. {
    10. for (var i = 0; i < src.Length; i++)
    11. {
    12. if (!has_dublicate(src, i, sequencelength))
    13. {
    14. result.Add(i + sequencelength);
    15. break;
    16. }
    17. }
    18. });
    19. //result.ForEach(Console.WriteLine);
    20. result.ForEach(x =>
    21. Console.WriteLine($"First marker after character {x}"));
    22. Console.WriteLine();
    23. Console.ReadLine();
    24. }

    Day07


    C#-Quellcode

    1. private static void Part01()
    2. {
    3. var space = ToSpaceSource();
    4. string command = string.Empty;
    5. var currentdir = space.Root[0];
    6. while (command.ToLower().Trim() != "$ exit" ||
    7. command.ToLower().Trim() != "exit")
    8. {
    9. command = Console.ReadLine().ToLower().Trim();
    10. if (command == "$ cls")
    11. {
    12. Console.Clear();
    13. continue;
    14. }
    15. if (command.StartsWith("$"))
    16. {
    17. var cmd = command.Split(new[] { " ", "=" }, StringSplitOptions.RemoveEmptyEntries);
    18. if (cmd[1] == "cd")
    19. {
    20. currentdir = cmd[2] switch
    21. {
    22. "/" => space.Root[0],
    23. ".." => currentdir?.Parent,
    24. _ => space.SearchDirectory(cmd[2]),
    25. };
    26. continue;
    27. }
    28. if (cmd[1] == "ls")
    29. {
    30. if (currentdir is null)
    31. currentdir = space.Root[0];
    32. foreach (var dir in currentdir.Directories)
    33. Console.WriteLine($"dir {dir.Name}");
    34. foreach (var file in currentdir.Files)
    35. Console.WriteLine($"{file.Size} {file.Name}");
    36. continue;
    37. }
    38. if (cmd[1] == "dirsize")
    39. {
    40. if (currentdir is null)
    41. currentdir = space.Root[0];
    42. var size = 0;
    43. Space.DirSize(currentdir, ref size);
    44. Console.WriteLine($"dir {currentdir?.Name} dirsize = {size}");
    45. continue;
    46. }
    47. if (cmd[1] == "assignment01")
    48. {
    49. if (currentdir is null)
    50. currentdir = space.Root[0];
    51. var spacesize = 0;
    52. var folders = new List<DirectoryEx>();
    53. if (cmd[2] == "min")
    54. {
    55. try
    56. {
    57. var sminsize = command.Split("min=", StringSplitOptions.RemoveEmptyEntries);
    58. var minsize = int.Parse(sminsize[1]);
    59. Space.FindFolderMin(currentdir, minsize, folders);
    60. var size = 0;
    61. foreach (var folder in folders)
    62. {
    63. size = 0;
    64. Space.DirSize(folder, ref size);
    65. spacesize += size;
    66. }
    67. Console.WriteLine($"Find {folders.Count} directory with total = {spacesize}");
    68. }
    69. catch { }
    70. continue;
    71. }
    72. if (cmd[2] == "max")
    73. {
    74. try
    75. {
    76. var smaxsize = command.Split("max=", StringSplitOptions.RemoveEmptyEntries);
    77. var maxsize = int.Parse(smaxsize[1]);
    78. Space.FindFolderMax(currentdir, maxsize, folders);
    79. var size = 0;
    80. foreach (var folder in folders)
    81. {
    82. size = 0;
    83. Space.DirSize(folder, ref size);
    84. spacesize += size;
    85. }
    86. Console.WriteLine($"Find {folders.Count} directory with total = {spacesize}");
    87. }
    88. catch { }
    89. continue;
    90. }
    91. }
    92. }
    93. }
    94. }​

    Sources

    C#-Quellcode

    1. private static Space ToSpaceSource()
    2. {
    3. var src = Sources();
    4. var rootname = src[0].Split(' ', StringSplitOptions.RemoveEmptyEntries)[1];
    5. var root = new DirectoryEx(rootname, null);
    6. var result = new Space(root);
    7. var dirname = src[1].Split(' ', StringSplitOptions.RemoveEmptyEntries)[1];
    8. var dir = new DirectoryEx(dirname, root);
    9. result.Add(dir, root.Name);
    10. result.Add(new DirectoryEx(src[2].Split(' ', StringSplitOptions.RemoveEmptyEntries)[1], dir), dir.Name);
    11. var filename = src[3].Split(' ', StringSplitOptions.RemoveEmptyEntries)[1];
    12. var filesize = int.Parse(src[3].Split(new[] { " ", "(", ")", "=", "," }, StringSplitOptions.RemoveEmptyEntries)[4]);
    13. result.Add(new FileEx(filename, filesize), src[2].Split(' ', StringSplitOptions.RemoveEmptyEntries)[1]);
    14. filename = src[4].Split(' ', StringSplitOptions.RemoveEmptyEntries)[1];
    15. filesize = int.Parse(src[4].Split(new[] { " ", "(", ")", "=", "," }, StringSplitOptions.RemoveEmptyEntries)[4]);
    16. result.Add(new FileEx(filename, filesize), dir.Name);
    17. filename = src[5].Split(' ', StringSplitOptions.RemoveEmptyEntries)[1];
    18. filesize = int.Parse(src[5].Split(new[] { " ", "(", ")", "=", "," }, StringSplitOptions.RemoveEmptyEntries)[4]);
    19. result.Add(new FileEx(filename, filesize), dir.Name);
    20. filename = src[6].Split(' ', StringSplitOptions.RemoveEmptyEntries)[1];
    21. filesize = int.Parse(src[6].Split(new[] { " ", "(", ")", "=", "," }, StringSplitOptions.RemoveEmptyEntries)[4]);
    22. result.Add(new FileEx(filename, filesize), dir.Name);
    23. filename = src[7].Split(' ', StringSplitOptions.RemoveEmptyEntries)[1];
    24. filesize = int.Parse(src[7].Split(new[] { " ", "(", ")", "=", "," }, StringSplitOptions.RemoveEmptyEntries)[4]);
    25. result.Add(new FileEx(filename, filesize), "/");
    26. filename = src[8].Split(' ', StringSplitOptions.RemoveEmptyEntries)[1];
    27. filesize = int.Parse(src[8].Split(new[] { " ", "(", ")", "=", "," }, StringSplitOptions.RemoveEmptyEntries)[4]);
    28. result.Add(new FileEx(filename, filesize), "/");
    29. dirname = src[9].Split(' ', StringSplitOptions.RemoveEmptyEntries)[1];
    30. dir = new DirectoryEx(dirname, root);
    31. result.Add(dir, root.Name);
    32. filename = src[10].Split(' ', StringSplitOptions.RemoveEmptyEntries)[1];
    33. filesize = int.Parse(src[10].Split(new[] { " ", "(", ")", "=", "," }, StringSplitOptions.RemoveEmptyEntries)[4]);
    34. result.Add(new FileEx(filename, filesize), dirname);
    35. filename = src[11].Split(' ', StringSplitOptions.RemoveEmptyEntries)[1];
    36. filesize = int.Parse(src[11].Split(new[] { " ", "(", ")", "=", "," }, StringSplitOptions.RemoveEmptyEntries)[4]);
    37. result.Add(new FileEx(filename, filesize), dirname);
    38. filename = src[12].Split(' ', StringSplitOptions.RemoveEmptyEntries)[1];
    39. filesize = int.Parse(src[12].Split(new[] { " ", "(", ")", "=", "," }, StringSplitOptions.RemoveEmptyEntries)[4]);
    40. result.Add(new FileEx(filename, filesize), dirname);
    41. filename = src[13].Split(' ', StringSplitOptions.RemoveEmptyEntries)[1];
    42. filesize = int.Parse(src[13].Split(new[] { " ", "(", ")", "=", "," }, StringSplitOptions.RemoveEmptyEntries)[4]);
    43. result.Add(new FileEx(filename, filesize), dirname);
    44. return result;
    45. }
    46. private static string[] Sources()
    47. {
    48. return new string[]
    49. {
    50. "- / (dir)",
    51. " - a (dir)",
    52. " - e (dir)",
    53. " - i (file, size=584)",
    54. " - f (file, size=29116)",
    55. " - g (file, size=2557)",
    56. " - h.lst (file, size=62596)",
    57. " - b.txt (file, size=14848514)",
    58. " - c.dat (file, size=8504156)",
    59. " - d (dir)",
    60. " - j (file, size=4060174)",
    61. " - d.log (file, size=8033020)",
    62. " - d.ext (file, size=5626152)",
    63. " - k (file, size=7214296)"
    64. };
    65. }

    Classes

    C#-Quellcode

    1. private class Space
    2. {
    3. public string Name { get; set; } = string.Empty;
    4. public List<DirectoryEx> Root { get; set; } = new List<DirectoryEx>();
    5. public Space(DirectoryEx directory, string name = "System")
    6. {
    7. this.Root.Add(directory);
    8. this.Name = name is null ? "System" : name;
    9. }
    10. public void Add(DirectoryEx directory, string dirname)
    11. {
    12. var dir = this.SearchDirectory(dirname);
    13. if (dir is not null) dir.Add(directory);
    14. }
    15. public void Add(FileEx file, string dirname)
    16. {
    17. var dir = this.SearchDirectory(dirname);
    18. if (dir is not null) dir.Add(file);
    19. }
    20. public DirectoryEx? SearchDirectory(string dirname)
    21. {
    22. foreach (var dir in this.Root)
    23. if (dirname.ToLower() == dir.Name.ToLower())
    24. return dir;
    25. foreach (var dir in this.Root)
    26. {
    27. var result = SearchDirectory(dir, dirname);
    28. if (result is not null) return result;
    29. }
    30. return default;
    31. }
    32. public static void DirSize(DirectoryEx? directory, ref int spacesize)
    33. {
    34. if (directory is null) return;
    35. spacesize += directory.Files.Sum(x => x.Size);
    36. foreach (var dir in directory.Directories)
    37. DirSize(dir, ref spacesize);
    38. }
    39. public static DirectoryEx? SearchDirectory(DirectoryEx directory, string dirname)
    40. {
    41. DirectoryEx? result = null;
    42. if (directory.Name.ToLower() == dirname.ToLower()) return directory;
    43. foreach (var dir in directory.Directories)
    44. {
    45. if (dir.Name.ToLower() == dirname.ToLower()) return dir;
    46. result = SearchDirectory(dir, dirname);
    47. if (result?.Name.ToLower() == dirname.ToLower()) return result;
    48. }
    49. return result;
    50. }
    51. public static void FindFolderMin(DirectoryEx? directory, int minsize, List<DirectoryEx> directories)
    52. {
    53. var spacesize = 0;
    54. DirSize(directory, ref spacesize);
    55. if (spacesize >= minsize && directory is not null)
    56. directories.Add(directory);
    57. if (directory?.Directories.Count() > 0)
    58. foreach (var dir in directory.Directories)
    59. FindFolderMin(dir, minsize, directories);
    60. }
    61. public static void FindFolderMax(DirectoryEx? directory, int maxsize, List<DirectoryEx> directories)
    62. {
    63. var spacesize = 0;
    64. DirSize(directory, ref spacesize);
    65. if (spacesize <= maxsize && directory is not null)
    66. directories.Add(directory);
    67. if (directory?.Directories.Count() > 0)
    68. foreach (var dir in directory.Directories)
    69. FindFolderMax(dir, maxsize, directories);
    70. }
    71. }
    72. private class DirectoryEx
    73. {
    74. public DirectoryEx? Parent { get; set; }
    75. public string Name { get; set; } = string.Empty;
    76. public List<FileEx> Files { get; set; } = new List<FileEx>();
    77. public List<DirectoryEx> Directories { get; set; } = new List<DirectoryEx>();
    78. public DirectoryEx(string name, DirectoryEx? parent)
    79. {
    80. this.Name = name;
    81. this.Parent = parent;
    82. }
    83. public void Add(DirectoryEx directory)
    84. {
    85. if (directory.Parent is null)
    86. directory.Parent = this;
    87. this.Directories.Add(directory);
    88. }
    89. public void Add(FileEx file)
    90. {
    91. this.Files.Add(file);
    92. }
    93. }
    94. private class FileEx
    95. {
    96. public int Size { get; set; } = -1;
    97. public string Name { get; set; } = string.Empty;
    98. public FileEx(string name, int size)
    99. {
    100. this.Name = name;
    101. this.Size = size;
    102. }
    103. }


    Day08

    C#-Quellcode

    1. private static void Part01()
    2. {
    3. var src = Sources()
    4. .Select(str => str
    5. .Select(s => int.Parse(s.ToString()))
    6. .ToArray())
    7. .ToArray();
    8. //In the beginning 16 trees are visible
    9. var result = 2 * src.Length + 2 * (src.Length - 2);
    10. for (var r = 1; r < src.Length - 1; r++)
    11. for (var c = 1; c < src[r].Length - 1; c++)
    12. {
    13. if (FromTop(src, c, r)) { result += 1; continue; }
    14. if (FromBottom(src, c, r)) { result += 1; continue; }
    15. if (FromLeft(src, c, r)) { result += 1; continue; }
    16. if (FromRigth(src, c, r)) { result += 1; continue; }
    17. }
    18. Console.WriteLine($"From outside are {result} trees visible.");
    19. Console.WriteLine();
    20. Console.ReadLine();
    21. }
    22. private static bool FromTop(int[][] grid, int x, int y)
    23. {
    24. var value = grid[x][y];
    25. for (var i = y - 1; i >= 0; i--)
    26. if (value <= grid[x][i])
    27. return false;
    28. return true;
    29. }
    30. private static bool FromBottom(int[][] grid, int x, int y)
    31. {
    32. var value = grid[x][y];
    33. for (var i = y + 1; i < grid.Length; i++)
    34. if (value <= grid[x][i])
    35. return false;
    36. return true;
    37. }
    38. private static bool FromLeft(int[][] grid, int x, int y)
    39. {
    40. var value = grid[x][y];
    41. for (var i = x - 1; i >= 0; i--)
    42. if (value <= grid[i][y])
    43. return false;
    44. return true;
    45. }
    46. private static bool FromRigth(int[][] grid, int x, int y)
    47. {
    48. var value = grid[x][y];
    49. for (var i = x + 1; i < grid[x].Length; i++)
    50. if (value <= grid[i][y])
    51. return false;
    52. return true;
    53. }

    Day 09

    Würde auch ohne Adjacent-Liste (in der Klasse Tail) funktionieren. Der Code müsste leicht angepasst werden.

    C#-Quellcode

    1. private static void Part01()
    2. {
    3. var visittail = new List<Point>();
    4. var head = new Head();
    5. var tail = new Tail();
    6. var cmds = CommandSource();
    7. Console.WriteLine($"head = {head.Value}");
    8. Console.WriteLine($"tail = {tail.Value}");
    9. Console.WriteLine();
    10. foreach (var cmd in cmds)
    11. SetCommand(head, tail, cmd, visittail);
    12. Console.WriteLine($"visite from tail: count = {visittail.Count}");
    13. visittail.ForEach(xy => Console.WriteLine(xy));
    14. Console.WriteLine();
    15. Console.ReadLine();
    16. }
    17. private static void SetCommand(Head head, Tail tail, string command, List<Point> visittail)
    18. {
    19. Console.WriteLine($"command = {command}");
    20. var tmp = command.Split(" ", StringSplitOptions.RemoveEmptyEntries);
    21. var cmd = tmp[0][0];
    22. var count = int.Parse(tmp[1]);
    23. for (var i = 0; i < count; i++)
    24. {
    25. head.SetCommand(cmd);
    26. tail.SetTail(head.Value);
    27. Console.WriteLine($"head = {head.Value}; tail = {tail.Value}");
    28. if (!visittail.Contains(tail.Value))
    29. visittail.Add(tail.Value);
    30. }
    31. Console.WriteLine();
    32. }

    Classes

    C#-Quellcode

    1. private class Head
    2. {
    3. public Point Value = Point.Empty;
    4. public Head() { }
    5. public Head(Point start) { this.Value = start; }
    6. public void SetCommand(char command)
    7. {
    8. switch (command)
    9. {
    10. case 'U': this.Value.Y = this.Value.Y + 1 ; return;
    11. case 'D': this.Value.Y = this.Value.Y - 1 ; return;
    12. case 'R': this.Value.X = this.Value.X + 1 ; return;
    13. case 'L': this.Value.X = this.Value.X - 1 ; return;
    14. }
    15. }
    16. }
    17. private class Tail
    18. {
    19. private Point MValue = Point.Empty;
    20. public Point Value
    21. {
    22. get => this.MValue;
    23. set
    24. {
    25. this.MValue = value;
    26. this.SetAdjacent();
    27. }
    28. }
    29. public Point[] Adjacent { get; set; } = Array.Empty<Point>();
    30. private decimal Sqrt5() => (decimal)Math.Sqrt(5.0);
    31. public Tail()
    32. {
    33. this.Adjacent = new Point[8];
    34. this.Value = Point.Empty;
    35. }
    36. public Tail(Point start):this()
    37. {
    38. this.Value = start;
    39. }
    40. public void SetTail(Point headvalue)
    41. {
    42. if (headvalue == this.MValue) return;
    43. if (this.Adjacent.Contains(headvalue)) return;
    44. var nf = this.NormalForm(headvalue);
    45. if (nf == 2M || nf == this.Sqrt5())
    46. this.Follow(headvalue);
    47. }
    48. private void Follow(Point headvalue)
    49. {
    50. var dif = this.Difference(headvalue);
    51. switch (dif.X)
    52. {
    53. case 2:
    54. this.MValue.Y = headvalue.Y;
    55. this.MValue.X = headvalue.X - 1;
    56. SetAdjacent();
    57. return;
    58. case -2:
    59. this.MValue.Y = headvalue.Y;
    60. this.MValue.X = headvalue.X + 1;
    61. SetAdjacent();
    62. return;
    63. }
    64. switch (dif.Y)
    65. {
    66. case 2:
    67. this.MValue.X = headvalue.X;
    68. this.MValue.Y = headvalue.Y - 1;
    69. SetAdjacent();
    70. return;
    71. case -2:
    72. this.MValue.X = headvalue.X;
    73. this.MValue.Y = headvalue.Y + 1;
    74. SetAdjacent();
    75. return;
    76. }
    77. }
    78. private void SetAdjacent()
    79. {
    80. int x = this.MValue.X, y = this.MValue.Y;
    81. this.Adjacent[0].X = x - 1; this.Adjacent[0].Y = y - 1;
    82. this.Adjacent[1].X = x; this.Adjacent[1].Y = y - 1;
    83. this.Adjacent[2].X = x + 1; this.Adjacent[2].Y = y - 1;
    84. this.Adjacent[3].X = x - 1; this.Adjacent[3].Y = y;
    85. this.Adjacent[4].X = x + 1; this.Adjacent[4].Y = y;
    86. this.Adjacent[5].X = x - 1; this.Adjacent[5].Y = y + 1;
    87. this.Adjacent[6].X = x; this.Adjacent[6].Y = y + 1;
    88. this.Adjacent[7].X = x + 1; this.Adjacent[7].Y = y + 1;
    89. }
    90. private decimal NormalForm(Point headvalue)
    91. {
    92. var dif = this.Difference(headvalue);
    93. return (decimal)Math.Sqrt(dif.X * dif.X + dif.Y * dif.Y);
    94. }
    95. private Point Difference(Point headvalue)
    96. {
    97. var result = Point.Empty;
    98. result.X = headvalue.X - this.MValue.X;
    99. result.Y = headvalue.Y - this.MValue.Y;
    100. return result;
    101. }
    102. }

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

    Tag 9
    Nach viel Nachdenken hab ich meiner Meinung nach eine clevere Lösung für Teil 1 gefunden.
    2 Koordinatensysteme zusammen genutzt. Einmal ein ganz normales X-Achse/Y-Achse mit 0/0 im Ursprung etc. und noch ein 5x5 Kästchen-Block durchnummeriert von 0-24 wobei das 12te Kästchen dem Ursprung des X-Y Systems gleich ist (siehe Foto). Nach dem Spielzug ist T automatisch wieder auf ID = 12 und H wird mit dem entsprechenden Offset neu positioniert (siehe Code :) ). Mich schon gefreut, da Teil 2 ja meist einfacher war. Jetzt erstmal frustriert aufgehört. Teil 2 auf den ersten kurzen Blick => WallOfText.

    AdventOfCode9.jpg

    Teil 1 C#
    Spoiler anzeigen

    C#-Quellcode

    1. using System.Drawing;
    2. var Lines = File.ReadAllLines("CodeAdvent_9.txt");
    3. int HeadId = 12;
    4. Point T_Coordinate = new(0,0);
    5. List<Point> TPoints = new();
    6. foreach (var line in Lines)
    7. {
    8. var MoveCmd = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
    9. for (int i = 0; i < int.Parse(MoveCmd[1]); i++)
    10. {
    11. Move activMove = new (MoveCmd[0], HeadId, T_Coordinate);
    12. T_Coordinate = activMove.T_Coordinate_AfterMove;
    13. HeadId = activMove.HeadId_AfterMove;
    14. TPoints.Add(T_Coordinate);
    15. }
    16. }
    17. Console.WriteLine($"Nr of fileds T visited at leaset once: {TPoints.Distinct().Count()}");
    18. class Move
    19. {
    20. public Move(string moveCmd, int headId_BeforeMove, Point t_coordinate_BeforeMove)
    21. {
    22. MoveCmd = moveCmd;
    23. HeadId_BeforeMove = headId_BeforeMove;
    24. T_Coordinate_BeforeMove = t_coordinate_BeforeMove;
    25. MoveHead();
    26. CheckIf_T_HasToMove();
    27. }
    28. private string MoveCmd { get; set; } = "";
    29. private int HeadId_BeforeMove { get; set; } = 0;
    30. public int HeadId_AfterMove { get; set; } = 0;
    31. //T shall always be ID=12
    32. private Point T_Coordinate_BeforeMove { get; set; } = new (0, 0);
    33. public Point T_Coordinate_AfterMove { get; set; } = new(0, 0);
    34. private int IdChangeBack_T_To12 = 0;
    35. private void MoveHead()
    36. {
    37. switch (MoveCmd)
    38. {
    39. case "U":
    40. HeadId_AfterMove = HeadId_BeforeMove - 5;
    41. break;
    42. case "D":
    43. HeadId_AfterMove = HeadId_BeforeMove + 5;
    44. break;
    45. case "L":
    46. HeadId_AfterMove = HeadId_BeforeMove - 1;
    47. break;
    48. case "R":
    49. HeadId_AfterMove = HeadId_BeforeMove + 1;
    50. break;
    51. default:
    52. break;
    53. }
    54. }
    55. private void CheckIf_T_HasToMove()
    56. {
    57. if (new List<int> { 6, 7, 8, 11, 12, 13, 16, 17, 18 }.Contains(HeadId_AfterMove))
    58. {//H stays in the 8 sourounding fields from T
    59. T_Coordinate_AfterMove = T_Coordinate_BeforeMove;
    60. IdChangeBack_T_To12 = 0;
    61. }//No Change--------------
    62. if (HeadId_AfterMove == 14)
    63. {//2xRight
    64. T_Coordinate_AfterMove = new Point(T_Coordinate_BeforeMove.X + 1, T_Coordinate_BeforeMove.Y);
    65. IdChangeBack_T_To12 = - 1;
    66. }
    67. if (HeadId_AfterMove == 10)
    68. {//2xLeft
    69. T_Coordinate_AfterMove = new Point(T_Coordinate_BeforeMove.X - 1, T_Coordinate_BeforeMove.Y);
    70. IdChangeBack_T_To12 = + 1;
    71. }
    72. if (HeadId_AfterMove == 2)
    73. {//2xUp
    74. T_Coordinate_AfterMove = new Point(T_Coordinate_BeforeMove.X, T_Coordinate_BeforeMove.Y + 1);
    75. IdChangeBack_T_To12 = + 5;
    76. }
    77. if (HeadId_AfterMove == 22)
    78. {//2xDown
    79. T_Coordinate_AfterMove = new Point(T_Coordinate_BeforeMove.X, T_Coordinate_BeforeMove.Y - 1);
    80. IdChangeBack_T_To12 = - 5;
    81. }/////////////////////////////////////////////////////////
    82. if (HeadId_AfterMove == 9 || HeadId_AfterMove == 3)
    83. {//1xRight1xUp1xRight //1xRight1xUp1xUp
    84. T_Coordinate_AfterMove = new Point(T_Coordinate_BeforeMove.X + 1, T_Coordinate_BeforeMove.Y + 1);
    85. IdChangeBack_T_To12 = + 4;
    86. }
    87. if (HeadId_AfterMove == 19 || HeadId_AfterMove == 23)
    88. {//1xRight1xDown1xRight
    89. T_Coordinate_AfterMove = new Point(T_Coordinate_BeforeMove.X + 1, T_Coordinate_BeforeMove.Y - 1);
    90. IdChangeBack_T_To12 = - 6 ;
    91. }
    92. if (HeadId_AfterMove == 5 || HeadId_AfterMove == 1)
    93. {//1xLeft1xUp1xLeft
    94. T_Coordinate_AfterMove = new Point(T_Coordinate_BeforeMove.X - 1, T_Coordinate_BeforeMove.Y + 1);
    95. IdChangeBack_T_To12 = + 6;
    96. }
    97. if (HeadId_AfterMove == 15 || HeadId_AfterMove == 21)
    98. {//1xLeft1xDown1xLeft
    99. T_Coordinate_AfterMove = new Point(T_Coordinate_BeforeMove.X - 1, T_Coordinate_BeforeMove.Y - 1);
    100. IdChangeBack_T_To12 = - 4;
    101. }
    102. //RESET GRIT: Finaly if T has moved -> move T and H back to Origin 0/0 --- T is auto back at 0/0 -- H has to keep its offset
    103. HeadId_AfterMove += IdChangeBack_T_To12;
    104. }
    105. }
    Bilder
    • AdventOfCode9.jpg

      6,65 MB, 4.032×3.024, 73 mal angesehen
    codewars.com Rank: 4 kyu

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

    Tag 09 - C# - Part 1 und 2:
    Spoiler anzeigen

    Ich hatte für Teil 1 die innere For für die Tails nicht und hatte nachdem ich teil 1 fertig gemacht habe dann einfach direkt alles in eine schleife gepackt.
    Man könnte natürlich auch 2 getrennte schleifen machen aber so ist das alles in einem. Geht sicherlich noch etwas eleganter.
    Am meisten Zeit hat mich tatsächlich gekostet wie ich hier ein ordentlichen Datentyp bekomme den ich NICHT vorher irgendwie festlegen muss wie groß er ist ( für X und Y ).
    Irgendwann ist der Groschen gefallen das es doch den Point gibt der genau das macht. Gibt es noch andere Datentypen?
    Bin offen für Vorschläge da mich das hier zum lösen des ersten Teils echt etwas kopfweh gemacht hat doch der 2 Part dann recht einfach war.

    C#-Quellcode

    1. using System.Drawing;
    2. string[] lines = File.ReadAllLines("Input.txt");
    3. Point Head = Point.Empty;
    4. int TailCount = 9;
    5. Point[] Tails = new Point[TailCount];
    6. List<Point> VisitedPointsFirstTail = new List<Point>();
    7. List<Point> VisitedPointsLastTail = new List<Point>();
    8. for (int i = 0; i < TailCount; i++)
    9. {
    10. Tails[i] = Point.Empty;
    11. }
    12. foreach (string line in lines)
    13. {
    14. string[] parts = line.Split(' ');
    15. Point MoveTo = Point.Empty;
    16. MoveTo = parts[0] switch
    17. {
    18. "R" => new Point(1, 0),
    19. "L" => new Point(-1, 0),
    20. "D" => new Point(0, -1),
    21. "U" => new Point(0, 1)
    22. };
    23. int Movements = Int32.Parse(parts[1]);
    24. for (int i = 0; i < Movements; i++)
    25. {
    26. Head.X += MoveTo.X;
    27. Head.Y += MoveTo.Y;
    28. for (int counter = 0; counter < TailCount; counter++)
    29. {
    30. int distanceToLastKnotX = 0;
    31. int distanceToLastKnotY = 0;
    32. if(counter == 0)
    33. {
    34. distanceToLastKnotX = Head.X - Tails[counter].X;
    35. distanceToLastKnotY = Head.Y - Tails[counter].Y;
    36. } else
    37. {
    38. distanceToLastKnotX = Tails[counter -1 ].X - Tails[counter].X;
    39. distanceToLastKnotY = Tails[counter -1 ].Y - Tails[counter].Y;
    40. }
    41. if (Math.Abs(distanceToLastKnotX) > 1 || Math.Abs(distanceToLastKnotY) > 1)
    42. {
    43. int absoluteX = Math.Sign(distanceToLastKnotX);
    44. int absoluteY = Math.Sign(distanceToLastKnotY);
    45. Tails[counter].X += absoluteX;
    46. Tails[counter].Y += absoluteY;
    47. }
    48. }
    49. VisitedPointsFirstTail.Add(Tails[0]);
    50. VisitedPointsLastTail.Add(Tails[TailCount - 1]);
    51. }
    52. }
    53. Console.WriteLine($"Part 1 First Tail: {VisitedPointsFirstTail.Distinct().Count()}");
    54. Console.WriteLine($"Part 2 Last Tail: {VisitedPointsLastTail.Distinct().Count()}");
    Grüße , xChRoNiKx

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

    Spoiler anzeigen

    Quellcode

    1. # https://adventofcode.com/2022/day/9
    2. # Repeat for each part
    3. foreach ($Part in @(2, 10)) {
    4. # Init hash set for positions
    5. [System.Collections.Generic.HashSet[String]]$Positions = @()
    6. # Init array list with knots
    7. [System.Collections.ArrayList]$Knots = @()
    8. for ($i = 0; $i -lt $Part; $i++) {
    9. [void]$Knots.Add([pscustomobject]@{
    10. Y = 0
    11. X = 0
    12. })
    13. }
    14. # Go through each line in input file
    15. foreach ($Line in Get-Content -Path $PSScriptRoot\day09_input.txt) {
    16. $LineValues = $Line.Split(" ")
    17. # Set direction to move
    18. $Y = 0
    19. $X = 0
    20. switch ($LineValues[0]) {
    21. "R" { $X = 1 }
    22. "L" { $X = -1 }
    23. "U" { $Y = 1 }
    24. "D" { $Y = -1 }
    25. }
    26. # Repeat movement for number of steps
    27. for ($n = 0; $n -lt [int]$LineValues[1]; $n++) {
    28. $Knots[0].Y = $Knots[0].Y + $Y
    29. $Knots[0].X = $Knots[0].X + $X
    30. # Update position for each knot
    31. for ($i = 1; $i -lt $Knots.Count; $i++) {
    32. $DiffY = $Knots[$i - 1].Y - $Knots[$i].Y
    33. $DiffX = $Knots[$i - 1].X - $Knots[$i].X
    34. if ([Math]::Abs($DiffX) -gt 1 -or [Math]::Abs($DiffY) -gt 1) {
    35. $Knots[$i].X = $Knots[$($i)].X + [Math]::Sign($DiffX)
    36. $Knots[$i].Y = $Knots[$($i)].Y + [Math]::Sign($DiffY)
    37. }
    38. }
    39. # Add last knot to hash set
    40. [void]$Positions.Add("[$($Knots[$($Knots.Count-1)].Y),$($Knots[$($Knots.Count-1)].X)]")
    41. }
    42. }
    43. # Result
    44. Write-Host "Part $Part result: $($Positions.Count)"
    45. }
    NETworkManager - A powerful tool for managing networks and troubleshoot network problems!
    Day10

    C#-Quellcode

    1. private static void Part01()
    2. {
    3. var instructions = Source();
    4. var cycle = 0;
    5. var value = 1; //start
    6. var check_cycle = 20;
    7. var check_cycle_step = 40;
    8. var sum_signal_strength = 0;
    9. [MethodImpl(MethodImplOptions.AggressiveInlining)]
    10. static void to_signal_strength(
    11. int signal_strength, int cycle, ref int sum_signal_strength,
    12. ref int check_cycle, int check_cycle_step = 40)
    13. {
    14. Console.WriteLine($"cycle: {cycle};\tsignal strength = {signal_strength}");
    15. sum_signal_strength += signal_strength;
    16. check_cycle += check_cycle_step;
    17. }
    18. foreach (var instruction in instructions)
    19. {
    20. if (instruction.StartsWith("noop"))
    21. {
    22. cycle++;
    23. if (cycle == check_cycle)
    24. to_signal_strength(value * cycle, cycle, ref sum_signal_strength, ref check_cycle, check_cycle_step);
    25. continue;
    26. }
    27. if (instruction.StartsWith("addx"))
    28. {
    29. var splitvalue = int.Parse(instruction.Split(" ")[1]);
    30. for (var i = 0; i < 2; i++)
    31. {
    32. cycle++;
    33. if (cycle == check_cycle)
    34. to_signal_strength(value * cycle, cycle, ref sum_signal_strength, ref check_cycle, check_cycle_step);
    35. }
    36. value += splitvalue;
    37. }
    38. }
    39. Console.WriteLine();
    40. Console.WriteLine($"sum of signal strengths is {sum_signal_strength}");
    41. Console.WriteLine();
    42. Console.ReadLine();
    43. }

    Optimation

    C#-Quellcode

    1. private static void Part01_Optimation()
    2. {
    3. var cycle = 0;
    4. var value = 1; //start
    5. var check_cycle = new[] { 20, 60, 100, 140, 180, 220, 0 };
    6. var sum_signal_strength = new List<int>();
    7. foreach (var instruction in Source())
    8. {
    9. if (instruction.StartsWith("noop"))
    10. {
    11. cycle++;
    12. if (cycle == check_cycle[sum_signal_strength.Count])
    13. sum_signal_strength.Add(value * cycle);
    14. }
    15. else
    16. {
    17. for (var i = 0; i < 2; i++)
    18. {
    19. cycle++;
    20. if (cycle == check_cycle[sum_signal_strength.Count])
    21. sum_signal_strength.Add(value * cycle);
    22. }
    23. value += int.Parse(instruction.Split(" ")[1]);
    24. }
    25. }
    26. Console.WriteLine($"signal strength:");
    27. sum_signal_strength.ForEach(Console.WriteLine);
    28. Console.WriteLine();
    29. Console.WriteLine($"sum of signal strengths is {sum_signal_strength.Sum()}");
    30. Console.WriteLine();
    31. Console.ReadLine();
    32. }​

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

    Tag 10

    Teil 1 C#
    Spoiler anzeigen

    C#-Quellcode

    1. var Lines = File.ReadAllLines("CodeAdvent_10.txt");
    2. var Sum = 1;
    3. var cycleOverAllCounter = 0;
    4. List<int> SignalStrengths = new();
    5. foreach (var line in Lines)
    6. {
    7. var opperationCycleCounter = 0;
    8. var lineValue = line.Split(' ');
    9. if (lineValue[0] == "addx")
    10. opperationCycleCounter = 2;
    11. if (lineValue[0] == "noop")
    12. opperationCycleCounter = 1;
    13. for (int i = 0; i < opperationCycleCounter; i++)
    14. {
    15. cycleOverAllCounter++;
    16. if (cycleOverAllCounter == 20 || cycleOverAllCounter == 60 || cycleOverAllCounter == 100 || cycleOverAllCounter == 140 || cycleOverAllCounter == 180 || cycleOverAllCounter == 220)
    17. SignalStrengths.Add(cycleOverAllCounter * Sum);
    18. }
    19. if (lineValue[0] == "addx")
    20. Sum += int.Parse(lineValue[1]);
    21. }
    22. Console.WriteLine($"Sum of signalstrengths: {SignalStrengths.Sum()}");


    Teil 2 C# (im Moment versteh ich die Frage nicht)
    codewars.com Rank: 4 kyu

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

    Day 10 Part 1 & Part 2 (war ne schöne Aufgabe)

    Spoiler anzeigen

    C#-Quellcode

    1. namespace Ten;
    2. using System.Diagnostics;
    3. public class Program
    4. {
    5. static List<Op> Ops = new();
    6. static CRT crt = new();
    7. static int X = 1;
    8. static void Main(string[] args)
    9. {
    10. IEnumerable<string> data = File.ReadLines("input.txt");
    11. for (int i = 0; i < data.Count(); i++)
    12. {
    13. var elements = data.ElementAt(i).SplitBy(" ");
    14. string opCode = elements.ElementAt(0);
    15. int value = elements.Count() > 1 ? int.Parse(elements.ElementAt(1)) : 0;
    16. Ops.Add(new Op(opCode, value));
    17. }
    18. int cycle = 1;
    19. //Für part 1
    20. // int result = 0;
    21. crt.SetX(X);
    22. while (true)
    23. {
    24. Op current = Ops.First();
    25. current.Cycles--;
    26. crt.DrawPixel(cycle);
    27. //Für part 1
    28. // if (cycle == 20 || cycle == 60 || cycle == 100 || cycle == 140 || cycle == 180 | cycle == 220)
    29. // result += cycle * X;
    30. if (current.Cycles == 0)
    31. {
    32. X += current.Value; //noop has value 0, so its ok.
    33. crt.SetX(X);
    34. Ops.RemoveAt(0);
    35. }
    36. cycle++;
    37. if (Ops.Count == 0)
    38. {
    39. //Für part 1
    40. // Log($"Execution finished, result={result}");
    41. crt.Output();
    42. break;
    43. }
    44. }
    45. }
    46. static void Log(string message) => Console.WriteLine(message);
    47. }
    48. public static class Extensions
    49. {
    50. public static IEnumerable<string> SplitBy(this string s, string d, bool keepEmpty = false)
    51. {
    52. if (keepEmpty)
    53. return s.Split(new string[] { d }, StringSplitOptions.None);
    54. else
    55. return s.Split(new string[] { d }, StringSplitOptions.RemoveEmptyEntries);
    56. }
    57. }
    58. class Op
    59. {
    60. public string OpCode { get; set; }
    61. public int Value { get; set; }
    62. public int Cycles { get; set; }
    63. public Op(string opCode, int value)
    64. {
    65. this.OpCode = opCode;
    66. this.Value = value;
    67. if (opCode == "noop") this.Cycles = 1;
    68. if (opCode == "addx") this.Cycles = 2;
    69. }
    70. public override string ToString() => $"{this.OpCode} {this.Value}";
    71. }
    72. class CRT
    73. {
    74. private string _display = string.Empty;
    75. private List<int> _pixelPositions = new();
    76. private int _position = 0;
    77. public void DrawPixel(int cycle)
    78. {
    79. if (_pixelPositions.Contains(_position))
    80. _display += "#";
    81. else
    82. _display += ".";
    83. _position++;
    84. if (cycle % 40 == 0)
    85. {
    86. _display += "\n";
    87. _position = 0;
    88. }
    89. }
    90. public void SetX(int x)
    91. {
    92. _pixelPositions.Clear();
    93. _pixelPositions.AddRange(new int[] { x - 1, x, x + 1 });
    94. }
    95. public void Output() => Console.WriteLine(_display);
    96. }

    Die Unendlichkeit ist weit. Vor allem gegen Ende. ?(
    Manche Menschen sind gar nicht dumm. Sie haben nur Pech beim Denken. 8o
    C# Tag 10 Part 1 und 2 zusammen
    Spoiler anzeigen

    C#-Quellcode

    1. ​string[] instructions = File.ReadAllLines("Input.txt");
    2. int X = 1;
    3. int cyclesDone = 0;
    4. int crtCycle = 1;
    5. List<int> whenToCheckSignalStrength = new List<int>() { 20, 60, 100, 140, 180, 220 };
    6. List<int> signalStrenthChecks = new List<int>();
    7. Console.WriteLine("Part 2 Output:");
    8. foreach (string instruction in instructions)
    9. {
    10. int cyclesNeeded = 0;
    11. string[] instructionParts = instruction.Split(' ');
    12. if (instructionParts[0].StartsWith("noop"))
    13. {
    14. cyclesNeeded = 1;
    15. }
    16. if (instructionParts[0].StartsWith("addx"))
    17. {
    18. cyclesNeeded = 2;
    19. }
    20. for (int i = 0; i < cyclesNeeded; i++)
    21. {
    22. if(crtCycle -1 >= X - 1 && crtCycle -1 <= X + 1)
    23. {
    24. Console.Write("#");
    25. } else
    26. {
    27. Console.Write(".");
    28. }
    29. if(crtCycle % 40 == 0 && crtCycle != 0)
    30. {
    31. Console.Write(Environment.NewLine);
    32. crtCycle = 0;
    33. }
    34. cyclesDone++;
    35. crtCycle++;
    36. if (whenToCheckSignalStrength.Contains(cyclesDone))
    37. {
    38. signalStrenthChecks.Add(cyclesDone * X);
    39. }
    40. if (i == cyclesNeeded - 1)
    41. {
    42. if (instructionParts.Length > 1)
    43. {
    44. X += Int32.Parse(instructionParts[1]);
    45. }
    46. }
    47. }
    48. }
    49. Console.WriteLine($"Part 1: {signalStrenthChecks.Sum()} ");
    Grüße , xChRoNiKx

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

    C#-Quellcode

    1. private static void Part01()
    2. {
    3. var rounds = 20;
    4. var worry_factor = 3;
    5. var monkeys = MonkeySource();
    6. for (var i = 0; i < rounds; i++)
    7. {
    8. foreach (var monkey in monkeys)
    9. {
    10. var count = monkey.Items.Count;
    11. for (var j = 0; j < count; j++)
    12. {
    13. var itm = monkey.Items.Dequeue();
    14. int worry_level = 0;
    15. var opn = monkey.OperationNumber != 0 ? monkey.OperationNumber : itm;
    16. switch (monkey.Operation)
    17. {
    18. case Operation.A: worry_level = itm + opn; break;
    19. case Operation.S: worry_level = itm - opn; break;
    20. case Operation.M: worry_level = itm * opn; break;
    21. case Operation.D: worry_level = itm / opn; break;
    22. }
    23. worry_level /= worry_factor;
    24. if (worry_level % monkey.DivisibleNumber == 0)
    25. monkeys[monkey.DivisibleTrueId].Items.Enqueue(worry_level);
    26. else monkeys[monkey.DivisibleFalseId].Items.Enqueue(worry_level);
    27. monkey.InspectedItems++;
    28. }
    29. }
    30. }
    31. var monkeyssort = monkeys.OrderByDescending(x=>x.InspectedItems).ToArray();
    32. var monkey_business = monkeyssort[0].InspectedItems * monkeyssort[1].InspectedItems;
    33. Console.WriteLine($"monkey business after {rounds} is {monkey_business}");
    34. Console.WriteLine();
    35. Console.ReadLine();
    36. }

    Sources

    C#-Quellcode

    1. private static Monkey[] MonkeySource()
    2. {
    3. var id = 0;
    4. var result = new List<Monkey>();
    5. Operation op = Operation.A;
    6. int opnumber = 0, divnumber = 0, trueid = 0, falseid = 0;
    7. foreach (var line in Source())
    8. {
    9. if (line.StartsWith("Monkey"))
    10. {
    11. result.Add(new Monkey(id++));
    12. continue;
    13. }
    14. if (line.Contains("Starting"))
    15. {
    16. var split = line.Split(new[] { " ", ":", "," }, StringSplitOptions.RemoveEmptyEntries);
    17. if (split is null) continue;
    18. var monkey = result.Last();
    19. for (var i = 2; i < split.Length; i++)
    20. monkey.Items.Enqueue(int.Parse(split[i]));
    21. continue;
    22. }
    23. if (line.Contains("Operation"))
    24. {
    25. var split = line.Split(new[] { " ", ":", "=" }, StringSplitOptions.RemoveEmptyEntries);
    26. if (split is null) continue;
    27. switch (split[3][0])
    28. {
    29. case '+': op = Operation.A; break;
    30. case '-': op = Operation.S; break;
    31. case '*': op = Operation.M; break;
    32. case '/': op = Operation.D; break;
    33. }
    34. if (int.TryParse(split[4], out int opn))
    35. opnumber = opn;
    36. else opnumber = 0;
    37. continue;
    38. }
    39. if (line.Contains("Test"))
    40. {
    41. var split = line.Split(new[] { " ", ":" }, StringSplitOptions.RemoveEmptyEntries);
    42. divnumber = int.Parse(split.Last());
    43. continue;
    44. }
    45. if (line.Contains("true: throw"))
    46. {
    47. var split = line.Split(new[] { " ", ":" }, StringSplitOptions.RemoveEmptyEntries);
    48. trueid = int.Parse(split.Last());
    49. continue;
    50. }
    51. if (line.Contains("false: throw"))
    52. {
    53. var split = line.Split(new[] { " ", ":" }, StringSplitOptions.RemoveEmptyEntries);
    54. falseid = int.Parse(split.Last());
    55. if (result.Count > 0)
    56. result.Last().SetParameters(op, opnumber, divnumber, trueid, falseid);
    57. }
    58. }
    59. return result.ToArray();
    60. }
    61. private static string[] Source()
    62. {
    63. return new string[]
    64. {
    65. "Monkey 0:",
    66. " Starting items: 79, 98",
    67. " Operation: new = old * 19",
    68. " Test: divisible by 23",
    69. " If true: throw to monkey 2",
    70. " If false: throw to monkey 3",
    71. "Monkey 1:",
    72. " Starting items: 54, 65, 75, 74",
    73. " Operation: new = old + 6",
    74. " Test: divisible by 19",
    75. " If true: throw to monkey 2",
    76. " If false: throw to monkey 0",
    77. "Monkey 2:",
    78. " Starting items: 79, 60, 97",
    79. " Operation: new = old * old",
    80. " Test: divisible by 13",
    81. " If true: throw to monkey 1",
    82. " If false: throw to monkey 3",
    83. "Monkey 3:",
    84. " Starting items: 74",
    85. " Operation: new = old + 3",
    86. " Test: divisible by 17",
    87. " If true: throw to monkey 0",
    88. " If false: throw to monkey 1"
    89. };
    90. }

    Classes

    C#-Quellcode

    1. private class Monkey
    2. {
    3. public int ID { get; private set; }
    4. public Queue<int> Items { get; set; }
    5. public Operation Operation { get; private set; }
    6. public int OperationNumber { get; private set; }
    7. public int DivisibleNumber { get; private set; }
    8. public int DivisibleTrueId { get; private set; }
    9. public int DivisibleFalseId { get; private set; }
    10. public int InspectedItems { get; set; }
    11. private Monkey()
    12. {
    13. this.ID = -1;
    14. this.Items = new Queue<int>();
    15. this.OperationNumber = -1;
    16. this.DivisibleNumber = -1;
    17. this.DivisibleTrueId = -1;
    18. this.DivisibleFalseId = -1;
    19. }
    20. public Monkey(int id) : this() { this.ID = id; }
    21. public void SetParameters(Operation op, int opnumber, int divnumber, int trueid, int falseid)
    22. {
    23. this.Operation = op;
    24. this.OperationNumber = opnumber;
    25. this.DivisibleNumber = divnumber;
    26. this.DivisibleTrueId = trueid;
    27. this.DivisibleFalseId = falseid;
    28. }
    29. }
    30. private enum Operation { A = 0, S = 1, M = 2, D = 3 }


    Optimation

    C#-Quellcode

    1. private static void Part01_Optimation()
    2. {
    3. var rounds = 20;
    4. var worry_factor = 3;
    5. var monkeys = MonkeyOptSource();
    6. for (var i = 0; i < rounds; i++)
    7. foreach (var monkey in monkeys)
    8. {
    9. var count = monkey[1].Count;
    10. for (var j = 0; j < count; j++)
    11. {
    12. int worry_level = 0;
    13. var itm = monkey[1][0];
    14. monkey[1].RemoveAt(0);
    15. var opn = monkey[0][2] != 0 ? monkey[0][2] : itm;
    16. switch ((Operation)monkey[0][1])
    17. {
    18. case Operation.A: worry_level = itm + opn; break;
    19. case Operation.S: worry_level = itm - opn; break;
    20. case Operation.M: worry_level = itm * opn; break;
    21. case Operation.D: worry_level = itm / opn; break;
    22. }
    23. worry_level /= worry_factor;
    24. if (worry_level % monkey[0][3] == 0)
    25. monkeys[monkey[0][4]][1].Add(worry_level);
    26. else monkeys[monkey[0][5]][1].Add(worry_level);
    27. monkey[0][6]++;
    28. }
    29. }
    30. var monkeyssort = monkeys.OrderByDescending(x => x[0][6]).ToArray();
    31. var monkey_business = (ulong)monkeyssort[0][0][6] * (ulong)monkeyssort[1][0][6];
    32. Console.WriteLine($"monkey business after {rounds} rounds is {monkey_business}");
    33. Console.WriteLine();
    34. Console.ReadLine();
    35. }

    Source

    C#-Quellcode

    1. private static List<int>[][] MonkeyOptSource()
    2. {
    3. return new List<int>[][]
    4. {
    5. new List<int>[]
    6. {
    7. new List<int>(new [] { 0, 2, 19, 23, 2, 3 , 0}),
    8. new List<int>(new [] { 79, 98 }),
    9. },
    10. new List<int>[]
    11. {
    12. new List<int>(new [] { 1, 0, 6, 19, 2, 0 , 0}),
    13. new List<int>(new [] { 54, 65, 75, 74 }),
    14. },
    15. new List<int>[]
    16. {
    17. new List<int>(new [] { 2, 2, 0, 13, 1, 3 , 0}),
    18. new List<int>(new [] { 79, 60, 97 }),
    19. },
    20. new List<int>[]
    21. {
    22. new List<int>(new [] { 3, 0, 3, 17, 0, 1 , 0}),
    23. new List<int>(new [] { 74 }),
    24. }
    25. };
    26. }

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

    Tag 11 C# - Part 1 und 2 in einem. Mehr dazu im Spoiler
    Spoiler anzeigen

    Kleine andere Frage dazu: WARUM kann ich nicht eine Liste für beide Aufrufe nutzen?
    Wenn ich in der Function SolvePuzzle etwas ändere an der Liste innerhalb dann verändert dies meine Liste von außerhalb. Ich hatte was gelesen von reference typen die nicht gecopy'd werden.
    Wie kann ich das verhindern? Das Problem ist mir jetzt seit mehreren Jahren C# noch nie untergekommen da ich meist immer eine Liste habe und diese auch verändern muss nur hier müsste ich ja mit einer Liste 2x eine Funktion mit anderen
    Parametern ausführen und da darf sich natürlich die Quellliste nicht ändern.

    Anfangs hatte ich mit LONG gearbeitet und nicht verstanden warum mein Ergebnis für Part 2 falsch ist. Gemerkt habe ich dann das Long wohl nicht ausreicht.
    Also habe ich dann BigInteger genommen. Problem -> Nach 3 Minuten rechnen war ich noch in Runde 900 ca.
    Irgendwie Multithreading geht ja nicht da die Operationen ja schon nacheinander ausgeführt werden müssen und nicht gleichzeitig laufen können.
    Dann eine Erkenntnis alle Zahlen mit denen ich teilen muss für das testen sind Primzahlen.
    Das heißt ich kann alle Primzahlen zusammen multiplizieren und dann das aktuelle WorryLevel modulo dieser zusammen multiplizierten Primzahl nehmen.
    So arbeite ich mit kleineren zahlen und alles ist schneller... Jetzt braucht das ganze nur ein paar Sekunden statt vorher wahrscheinlich Stunden.
    Wahrscheinlich kann ich jetzt dann auch wieder mit Long arbeiten allerdings hatte ich jetzt keine Lust mehr das zu ändern. Hauptsache gelöst.
    Geht sicher auch eleganter.

    C#-Quellcode

    1. using System.Numerics;
    2. List<Monkey> LMonkeys = File.ReadAllLines("Input.txt").Chunk(7).Select(m => new Monkey(m)).ToList();
    3. List<Monkey> LMonkeys2 = File.ReadAllLines("Input.txt").Chunk(7).Select(m => new Monkey(m)).ToList();
    4. BigInteger part1 = SolvePuzzle(LMonkeys, 20).OrderByDescending(x => x.InspectedItems).Take(2).Select(x => x.InspectedItems).Aggregate((current, next) => current * next);
    5. BigInteger part2 = SolvePuzzle(LMonkeys2, 10000, false).OrderByDescending(x => x.InspectedItems).Take(2).Select(x => x.InspectedItems).Aggregate((current, next) => current * next);
    6. Console.WriteLine($"Part 1: {part1}");
    7. Console.WriteLine($"Part 2: {part2}");
    8. List<Monkey> SolvePuzzle(List<Monkey> originalMonkeys, int rounds, bool isPart1 = true)
    9. {
    10. BigInteger mod = 1;
    11. List<Monkey> monkeys = originalMonkeys;
    12. foreach (Monkey monkey in monkeys)
    13. {
    14. mod *= monkey.CheckingDivisor;
    15. }
    16. for (int i = 1; i < rounds +1; i++)
    17. {
    18. for (int monkeyNumber = 0; monkeyNumber < monkeys.Count; monkeyNumber++)
    19. {
    20. if (monkeys[monkeyNumber].Items.Count == 0) continue;
    21. for (int itemNumber = 0; itemNumber < monkeys[monkeyNumber].Items.Count; itemNumber++)
    22. {
    23. BigInteger newItemWorryLevel = monkeys[monkeyNumber].CalculateNewWorryLevel(monkeys[monkeyNumber].Items[itemNumber] % mod);
    24. if (isPart1)
    25. {
    26. newItemWorryLevel = newItemWorryLevel / monkeys[monkeyNumber].MonkeyBoredDivisor;
    27. }
    28. if (newItemWorryLevel % monkeys[monkeyNumber].CheckingDivisor == 0)
    29. {
    30. monkeys[monkeys[monkeyNumber].IfTrueThrowTo].Items.Add(newItemWorryLevel);
    31. }
    32. else
    33. {
    34. monkeys[monkeys[monkeyNumber].IfFalseThrowTo].Items.Add(newItemWorryLevel);
    35. }
    36. }
    37. monkeys[monkeyNumber].InspectedItems += monkeys[monkeyNumber].Items.Count;
    38. monkeys[monkeyNumber].Items.Clear();
    39. }
    40. if (i % 1000 == 0 || i == 1 || i == 20)
    41. {
    42. Console.WriteLine($"== After round {i} ==");
    43. for (int m = 0; m < monkeys.Count; m++)
    44. {
    45. Console.WriteLine($"Monkey {m} inspected items {monkeys[m].InspectedItems} times.");
    46. }
    47. }
    48. }
    49. return monkeys;
    50. }
    51. public class Monkey
    52. {
    53. public List<BigInteger> Items { get; set; } = new List<BigInteger>();
    54. public BigInteger CheckingDivisor { get; set; }
    55. public int MonkeyBoredDivisor { get; set; } = 3;
    56. public int IfTrueThrowTo { get; set; }
    57. public int IfFalseThrowTo { get; set; }
    58. public BigInteger InspectedItems { get; set; } = 0;
    59. private string Operant = "";
    60. private string WorryLevelToAdd = "";
    61. public Monkey(string[] monkeyPropertys)
    62. {
    63. Items.AddRange(monkeyPropertys[1].Split(':')[1].Split(',').Select(i => BigInteger.Parse(i.Trim())));
    64. CheckingDivisor = BigInteger.Parse(monkeyPropertys[3].Replace(" Test: divisible by ",""));
    65. IfTrueThrowTo = Int32.Parse(monkeyPropertys[4].Replace(" If true: throw to monkey ", ""));
    66. IfFalseThrowTo = Int32.Parse(monkeyPropertys[5].Replace(" If false: throw to monkey ", ""));
    67. string[] operations = monkeyPropertys[2].Replace(" Operation: new = ", "").Split(' ');
    68. Operant = operations[1];
    69. WorryLevelToAdd = operations[2];
    70. }
    71. public BigInteger CalculateNewWorryLevel(BigInteger worryLevel)
    72. {
    73. BigInteger secondNumber = 0;
    74. if (WorryLevelToAdd.Contains("old"))
    75. {
    76. secondNumber = worryLevel;
    77. } else
    78. {
    79. secondNumber = BigInteger.Parse(WorryLevelToAdd);
    80. }
    81. return Operant switch
    82. {
    83. "*" => worryLevel * secondNumber,
    84. "/" => worryLevel / secondNumber,
    85. "+" => worryLevel + secondNumber,
    86. "-" => worryLevel - secondNumber,
    87. };
    88. }
    89. }

    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“ ()

    Tag 11

    Teil 1 C#
    Spoiler anzeigen

    C#-Quellcode

    1. #region Main
    2. using System.Runtime.CompilerServices;
    3. using System.Text.RegularExpressions;
    4. var Lines = File.ReadAllLines("CodeAdvent_11T.txt");
    5. List<Monkey> Monkeys = new();
    6. var rounds = 20;
    7. for (int i = 0; i < Lines.Count(); i++)
    8. {
    9. if (Regex.IsMatch(Lines[i], @"Monkey"))
    10. {//Create Obj Monkey from input.txt add to List
    11. var id = int.Parse(Regex.Match(Lines[i], @"\d+").Value);
    12. var itemsMatches = Regex.Matches(Lines[i + 1], @"\d+").ToList();
    13. List<long> items = new();
    14. foreach (var item in itemsMatches)
    15. {
    16. items.Add(int.Parse(item.Value));
    17. }
    18. var isMultiply = Regex.IsMatch(Lines[i + 2], @"\*");
    19. var operatorFactor = Lines[i + 2].Split(' ').Last();
    20. var divisor = int.Parse(Regex.Match(Lines[i + 3], @"\d+").Value);
    21. var targetMonkeyId_True = int.Parse(Regex.Match(Lines[i + 4], @"\d+").Value);
    22. var targetMonkeyId_False = int.Parse(Regex.Match(Lines[i + 5], @"\d+").Value);
    23. Monkeys.Add(new Monkey(id, items, isMultiply, operatorFactor, divisor, targetMonkeyId_True, targetMonkeyId_False));
    24. }
    25. }
    26. for (int i = 0; i < rounds; i++)
    27. {
    28. foreach (var m in Monkeys)
    29. {
    30. var throwObjs = m.InspectItemThrowTo();
    31. foreach (var item in throwObjs)
    32. {
    33. var targetMonkey = Monkeys.Where(x => x.Id == item.TargetMonkeyIds).First();
    34. targetMonkey.Items.Add(item.Item);
    35. }
    36. }
    37. }
    38. foreach (var m in Monkeys)
    39. {
    40. Console.WriteLine(m.InspectionCount);
    41. }
    42. var res = Monkeys.OrderBy(x => x.InspectionCount).ToList();
    43. res.Reverse();
    44. Console.WriteLine($"\n{res[0].InspectionCount * res[1].InspectionCount}");
    45. #endregion ^^Main
    46. #region Classes
    47. class Monkey
    48. {
    49. public Monkey(int id, List<long> items, bool isMultiply, string operationFactor, int divisor, int targetMonkeyId_True, int targetMonkeyId_False)
    50. {
    51. Id = id;
    52. Items = items;
    53. IsMultiply = isMultiply;
    54. OperationFactor = operationFactor;
    55. Divisor = divisor;
    56. TargetMonkeyId_True = targetMonkeyId_True;
    57. TargetMonkeyId_False = targetMonkeyId_False;
    58. }
    59. public int Id { get; set; } = 0;
    60. public List<long> Items { get; set; } = new();
    61. private bool IsMultiply { get; set; } = false;
    62. private string OperationFactor { get; set; } = string.Empty;
    63. private int Divisor { get; set; } = 0;
    64. private int TargetMonkeyId_True { get; set; } = 0;
    65. private int TargetMonkeyId_False { get; set; } = 0;
    66. public long InspectionCount { get; set; } = 0;
    67. public List<MonkeyTarget> InspectItemThrowTo()
    68. {
    69. List<MonkeyTarget> monkeyTargets = new();
    70. foreach (var item in Items)
    71. {
    72. long factor = 0;
    73. if (OperationFactor == "old")
    74. factor = item;
    75. else
    76. factor = int.Parse(OperationFactor);
    77. decimal worryValue = IsMultiply ? item * factor : item + factor;
    78. var newWorryValue = (int)Math.Floor(worryValue / 3);
    79. //long newWorryValue = IsMultiply ? item * factor : item + factor;
    80. ////das geht bis 1000 Runden dann falsche Werte
    81. if (newWorryValue % Divisor == 0)
    82. {
    83. monkeyTargets.Add(new(TargetMonkeyId_True, newWorryValue));
    84. }
    85. else
    86. {
    87. monkeyTargets.Add(new(TargetMonkeyId_False, newWorryValue));
    88. }
    89. InspectionCount++;
    90. }
    91. Items.Clear();
    92. return monkeyTargets;
    93. }
    94. }
    95. class MonkeyTarget
    96. {
    97. public MonkeyTarget(int targetMonkeyIds, long item)
    98. {
    99. TargetMonkeyIds = targetMonkeyIds;
    100. Item = item;
    101. }
    102. public int TargetMonkeyIds { get; set; } = 0;
    103. public long Item { get; set; } = 0;
    104. }
    105. #endregion Classes


    Teil 2# (bis 1000 Runden geht alles noch dann werden die Zahlen zu groß)

    @xChRoNiKx So wie ich deine Zusatzfrage verstanden habe, hast Du die Antwort schon gefunden. Listen sind ReferenceType und im Speicher liegen an der Adresse die Daten. Egal wie häufig Du die kopierst etc. Es gibt denke ich keinen einfachen Weg das zu umgehen, ala AsValue.
    Hab es selber nochmal probiert:
    Spoiler anzeigen

    C#-Quellcode

    1. List<Kunde> Kunden1 = new List<Kunde>
    2. {
    3. new("Anton"),
    4. new("Bernd"),
    5. new("Cecil"),
    6. new("Donna"),
    7. new("Ernie")
    8. };
    9. List<Kunde> Kunden2 = new();
    10. Kunden2 = Kunden1;
    11. foreach (var k in Kunden1)
    12. {
    13. Console.WriteLine(k.Name);
    14. }
    15. //List 3 wird nicht geändert
    16. List<Kunde> Kunden3 = new();
    17. foreach (var k in Kunden1)
    18. {
    19. Kunden3.Add(k);
    20. }
    21. ChangeLists(Kunden2);
    22. Console.WriteLine($"\n----List1 ist auch reverse----");
    23. foreach (var k in Kunden1)
    24. {
    25. Console.WriteLine(k.Name);
    26. }
    27. Console.WriteLine("-----------");
    28. foreach (var k in Kunden2)
    29. {
    30. Console.WriteLine(k.Name);
    31. }
    32. Console.WriteLine("-----------");
    33. foreach (var k in Kunden3)
    34. {
    35. Console.WriteLine(k.Name);
    36. }
    37. Console.WriteLine("-----------");
    38. //Methode
    39. void ChangeLists(List<Kunde> kunden)
    40. {
    41. kunden.Reverse();
    42. }
    43. ///Class
    44. class Kunde
    45. {
    46. public Kunde(string name)
    47. {
    48. Name = name;
    49. }
    50. public Guid Id { get; set; } = Guid.NewGuid();
    51. public string Name { get; set; } = string.Empty;
    52. }


    Output:
    Spoiler anzeigen
    Bernd
    Cecil
    Donna
    Ernie

    ----List1 ist auch reverse----
    Ernie
    Donna
    Cecil
    Bernd
    Anton
    -----------
    Ernie
    Donna
    Cecil
    Bernd
    Anton
    -----------
    Anton
    Bernd
    Cecil
    Donna
    Ernie
    -----------
    codewars.com Rank: 4 kyu

    Dieser Beitrag wurde bereits 2 mal editiert, zuletzt von „nogood“ ()

    Tag 10 / PowerShell

    Spoiler anzeigen

    Quellcode

    1. # https://adventofcode.com/2022/day/10
    2. $X = 1
    3. $Loops = 0
    4. $CyclesToCheck = @(20, 60, 100, 140, 180, 220)
    5. [System.Collections.ArrayList]$SignalStrengths = @()
    6. function LoopAction() {
    7. # Part 1
    8. if ($CyclesToCheck.Contains($Loops)) {
    9. [void]$SignalStrengths.Add($Loops * $X)
    10. }
    11. # Part 2
    12. $CrtPixel = ($Loops - 1) % 40
    13. $PrintValue = "."
    14. if ([Math]::Abs($CrtPixel - $X) -lt 2) {
    15. $PrintValue = "X"
    16. }
    17. Write-Host $PrintValue -NoNewline
    18. if ($CrtPixel -eq 39) {
    19. Write-Host ""
    20. }
    21. }
    22. foreach ($Line in Get-Content $PSScriptRoot\input.txt) {
    23. $LineValues = $Line.Split(" ")
    24. if ($LineValues[0] -eq "noop") {
    25. $Loops++
    26. LoopAction
    27. continue
    28. }
    29. if ($LineValues[0] -eq "addx") {
    30. for ($i = 0; $i -lt 2; $i++) {
    31. $Loops++
    32. LoopAction
    33. if ($i -eq 0) { continue }
    34. $X += [Int]::Parse($LineValues[1])
    35. }
    36. }
    37. }
    38. # Part 1
    39. Write-Host "Part 1: $(($SignalStrengths | Measure-Object -Sum).Sum)"


    Tag 11 / PowerShell

    Part 1
    Spoiler anzeigen

    Quellcode

    1. # https://adventofcode.com/2022/day/11
    2. $Text = Get-Content -Path $PSScriptRoot\input.txt
    3. [System.Collections.ArrayList]$Monkeys = @()
    4. <#
    5. Example monkey in the list:
    6. Monkey : 0
    7. Items : {79, 98}
    8. Operation : *,19
    9. Test : 23
    10. NextMonkeyTrue : 2
    11. NextMonkeyFalse : 3
    12. #>
    13. for($i = 0; $i -lt $Text.Count; $i += 7) {
    14. [System.Collections.ArrayList]$Items = @()
    15. $($Text[$i+1].Trim().Split(":")[1].Replace(" ","").Split(",")) | ForEach-Object { [void]$Items.Add([int]$_) }
    16. [void]$Monkeys.Add([pscustomobject]@{
    17. Monkey = $Text[$i].Trim().Split(" ")[1].Split(":")[0]
    18. Items = $Items
    19. Operation = $Text[$i+2].Trim().Split("=")[1].Trim().Split(" ")[1..2] -join ","
    20. Test = [int]$($Text[$i+3].Trim().Split(" ")[3])
    21. NextMonkeyTrue = [int]$($Text[$i+4].Trim().Split(" ")[5])
    22. NextMonkeyFalse = [int]$($Text[$i+5].Trim().Split(" ")[5])
    23. Inspected = 0
    24. })
    25. }
    26. for($i = 0; $i -lt 20; $i++) {
    27. foreach($Monkey in $Monkeys) {
    28. $Operations = $Monkey.Operation.Split(",")
    29. foreach($Item in $Monkey.Items) {
    30. $Monkey.Inspected++
    31. $OperationValue = $Operations[1]
    32. if($OperationValue -eq "old") {
    33. $OperationValue = $Item
    34. }
    35. switch($Operations[0]) {
    36. "+" { $Result = $Item + $OperationValue }
    37. "*" { $Result = $Item * $OperationValue }
    38. }
    39. $NewWorryLevel = [Math]::Floor($Result / 3)
    40. $NewMonkey = $NewWorryLevel%$Monkey.Test -eq 0 ? $Monkey.NextMonkeyTrue : $Monkey.NextMonkeyFalse
    41. [void]$Monkeys[$NewMonkey].Items.Add($NewWorryLevel)
    42. }
    43. $Monkey.Items.Clear()
    44. }
    45. }
    46. $MonkeysInspected = ($Monkeys.Inspected | Sort-Object -Descending)[0..1]
    47. Write-Host "Part 1: $($MonkeysInspected[0] * $MonkeysInspected[1])"


    Part 2

    Für die Berechnung des Worry Levels gibt es hier eine sehr gute Erklärung: reddit.com/r/adventofcode/comm…tm_medium=web2x&context=3

    Spoiler anzeigen

    Quellcode

    1. # https://adventofcode.com/2022/day/11
    2. function Gcd($a, $b) {
    3. if ($a -eq 0) { $b }
    4. elseif ($b -eq 0) { $a }
    5. else { Gfc -a ($b % $a) -b $a }
    6. }
    7. function Lcm($a, $b) {
    8. ($a * $b) / $(Gcd -a $a -b $b)
    9. }
    10. $Text = Get-Content -Path $PSScriptRoot\input.txt
    11. [System.Collections.ArrayList]$Monkeys = @()
    12. <#
    13. Example monkey in the list:
    14. Monkey : 0
    15. Items : {79, 98}
    16. Operation : *,19
    17. Test : 23
    18. NextMonkeyTrue : 2
    19. NextMonkeyFalse : 3
    20. #>
    21. for ($i = 0; $i -lt $Text.Count; $i += 7) {
    22. [System.Collections.ArrayList]$Items = @()
    23. $($Text[$i + 1].Trim().Split(":")[1].Replace(" ", "").Split(",")) | ForEach-Object { [void]$Items.Add([int64]$_) }
    24. [void]$Monkeys.Add([pscustomobject]@{
    25. Monkey = $Text[$i].Trim().Split(" ")[1].Split(":")[0]
    26. Items = $Items
    27. Operation = $Text[$i + 2].Trim().Split("=")[1].Trim().Split(" ")[1..2] -join ","
    28. Test = [int]$($Text[$i + 3].Trim().Split(" ")[3])
    29. NextMonkeyTrue = [int]$($Text[$i + 4].Trim().Split(" ")[5])
    30. NextMonkeyFalse = [int]$($Text[$i + 5].Trim().Split(" ")[5])
    31. Inspected = 0
    32. })
    33. }
    34. # Get the Least Common Multiple of all monkeys
    35. $LCM = $Monkeys[0].Test
    36. for ($i = 1; $i -lt $Monkeys.Count; $i++) {
    37. $LCM = Lcm -a $LCM -b $Monkeys[$i].Test
    38. }
    39. for ($i = 0; $i -lt 10000; $i++) {
    40. foreach ($Monkey in $Monkeys) {
    41. $Operations = $Monkey.Operation.Split(",")
    42. foreach ($Item in $Monkey.Items) {
    43. $Monkey.Inspected++
    44. $OperationValue = $Operations[1]
    45. if ($OperationValue -eq "old") {
    46. $OperationValue = $Item
    47. }
    48. switch ($Operations[0]) {
    49. "+" { $Result = $Item + $OperationValue }
    50. "*" { $Result = $Item * $OperationValue }
    51. }
    52. # Mod by the LCM to get the new worry level and keep the number low
    53. $NewWorryLevel = $Result % $LCM
    54. $NewMonkey = $NewWorryLevel % $Monkey.Test -eq 0 ? $Monkey.NextMonkeyTrue : $Monkey.NextMonkeyFalse
    55. [void]$Monkeys[$NewMonkey].Items.Add($NewWorryLevel)
    56. }
    57. $Monkey.Items.Clear()
    58. }
    59. }
    60. $MonkeysInspected = ($Monkeys.Inspected | Sort-Object -Descending)[0..1]
    61. Write-Host "Part 2: $($MonkeysInspected[0] * $MonkeysInspected[1])"


    Edit: OK den ggT und kgV zu berechnen ist unnötig. Sind ja bereits Primzahlen.

    Das hier reicht um auf Mod zu kommen:
    Spoiler anzeigen

    Quellcode

    1. $Mod = $Monkeys[0].Test
    2. for ($i = 1; $i -lt $Monkeys.Count; $i++) {
    3. $Mod *= $Monkeys[$i].Test
    4. }
    NETworkManager - A powerful tool for managing networks and troubleshoot network problems!

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