From 47b55aaaec1de8bee2611a22e992a17f7093f11b Mon Sep 17 00:00:00 2001 From: TiagoRG Date: Sat, 24 Jun 2023 22:26:39 +0100 Subject: [PATCH] Some refactoring --- README.md | 3 + Utils/Extensions/LinqExtensions.cs | 48 +++++------ Utils/Extensions/MathExtensions.cs | 18 +++-- Year2022/Day1.cs | 31 +++---- Year2022/Day10.cs | 71 ++++++++-------- Year2022/Day11.cs | 92 +++++++++++---------- Year2022/Day2.cs | 26 +++--- Year2022/Day3.cs | 72 ++++++++--------- Year2022/Day4.cs | 39 ++++----- Year2022/Day5.cs | 65 +++++++-------- Year2022/Day6.cs | 14 ++-- Year2022/Day7.cs | 61 +++++++------- Year2022/Day8.cs | 125 +++++++++++++++-------------- Year2022/Day9.cs | 44 +++++----- Year2022/Loader2022.cs | 3 +- 15 files changed, 366 insertions(+), 346 deletions(-) diff --git a/README.md b/README.md index 6439a99..3e0c351 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,13 @@ # Advent of Code + ## Solutions for the AoC Challenges, all in C# + ### They might not be the best solutions but they work and that's the important part of a coders job :xdd: ## Solutions organized by year, 1 file per day. ### [2022](https://github.com/TiagoRG/AdventOfCode/tree/main/AdventOfCode/Year2022) + * [Day 1](https://github.com/TiagoRG/AdventOfCode/tree/main/AdventOfCode/Year2022/Day1.cs) * [Day 2](https://github.com/TiagoRG/AdventOfCode/tree/main/AdventOfCode/Year2022/Day2.cs) * [Day 3](https://github.com/TiagoRG/AdventOfCode/tree/main/AdventOfCode/Year2022/Day3.cs) diff --git a/Utils/Extensions/LinqExtensions.cs b/Utils/Extensions/LinqExtensions.cs index 39c10ef..9cc198c 100644 --- a/Utils/Extensions/LinqExtensions.cs +++ b/Utils/Extensions/LinqExtensions.cs @@ -3,7 +3,7 @@ namespace AdventOfCode.Utils.Extensions; public static class LinqExtensions { /// - /// Returns a slice of the given list + /// Returns a slice of the given list /// /// The list you pretend to slice /// The first index of the slice @@ -11,49 +11,49 @@ public static class LinqExtensions /// public static List Sublist(this List list, int startIndex, int endIndex = default) { - List result = new List(); + var result = new List(); if (endIndex == default) endIndex = list.Count; - for (int i = startIndex; i < endIndex; i++) + for (var i = startIndex; i < endIndex; i++) result.Add(list[i]); return result; } /// - /// Returns a column of a give matrix list + /// Returns a column of a give matrix list /// /// 2 dimensions list /// Column index /// public static List GetColumn(this List> list, int column) { - List result = new List(); - foreach (List row in list) result.AddRange(row.Where((t, i) => i == column)); + var result = new List(); + foreach (var row in list) result.AddRange(row.Where((t, i) => i == column)); return result; } /// - /// Reverses a given list + /// Reverses a given list /// /// The list to reverse /// The reversed list public static List Reversed(this List list) { - List reversed = new List(); - for (int i = 0; i < list.Count; i++) - reversed.Add(list[list.Count-1-i]); + var reversed = new List(); + for (var i = 0; i < list.Count; i++) + reversed.Add(list[list.Count - 1 - i]); return reversed; } /// - /// Clones a list of elements + /// Clones a list of elements /// /// The original list /// A copy of the original list public static List Clone(this List original) { - List ret = new List(original.Count); - foreach (T element in original) + var ret = new List(original.Count); + foreach (var element in original) ret.Add(element); return ret; } @@ -63,39 +63,39 @@ public static class LinqExtensions where TValue : ICloneable where TKey : notnull { - Dictionary ret = new Dictionary(original.Count, original.Comparer); - foreach (KeyValuePair entry in original) - ret.Add(entry.Key, (TValue) entry.Value.Clone()); + var ret = new Dictionary(original.Count, original.Comparer); + foreach (var entry in original) + ret.Add(entry.Key, (TValue)entry.Value.Clone()); return ret; } - + public static Dictionary> Clone (this Dictionary> original) where TKey : notnull { - Dictionary> ret = new Dictionary>(original.Count, original.Comparer); - foreach (KeyValuePair> entry in original) + var ret = new Dictionary>(original.Count, original.Comparer); + foreach (var entry in original) ret.Add(entry.Key, entry.Value.Clone()); return ret; } public static void Fill(this List list, int count, T element) - where T : ICloneable + where T : ICloneable { - for (int i = 0; i < count; i++) + for (var i = 0; i < count; i++) list.Add(element); } public static void Fill(this List> list, int count, List element) { - for (int i = 0; i < count; i++) + for (var i = 0; i < count; i++) list.Add(element.Clone()); } public static void Set(this List list, int index, T element) { - List backup = list.Clone(); + var backup = list.Clone(); list.Clear(); - for (int i = 0; i < list.Count; i++) list.Add(i == index ? element : list[i]); + for (var i = 0; i < list.Count; i++) list.Add(i == index ? element : list[i]); } } \ No newline at end of file diff --git a/Utils/Extensions/MathExtensions.cs b/Utils/Extensions/MathExtensions.cs index 384587d..1c9878a 100644 --- a/Utils/Extensions/MathExtensions.cs +++ b/Utils/Extensions/MathExtensions.cs @@ -18,7 +18,7 @@ public static class MathExtensions { Convert.ToInt32(s); } - catch (FormatException ignored) + catch (FormatException) { return false; } @@ -28,30 +28,32 @@ public static class MathExtensions public static ulong ProductOfMax(this List list, int maxCount) { - List maxList = new List(maxCount); + var maxList = new List(maxCount); - foreach (ulong number in list) + foreach (var number in list) { if (maxList.Count < maxList.Capacity) + { maxList.Add(number); - else - if (number > maxList.Min()) + } + else if (number > maxList.Min()) { maxList.RemoveAt(0); maxList.Add(number); } + maxList.Sort(); } ulong product = 1; - maxList.ForEach(n => product*=n); + maxList.ForEach(n => product *= n); return product; } public static int LeastCommonMultiplier(this List list) { - int lcm = 1; - foreach (int i in list) + var lcm = 1; + foreach (var i in list) lcm *= i / MathTools.GreatCommonDivider(lcm, i); return lcm; } diff --git a/Year2022/Day1.cs b/Year2022/Day1.cs index 40ae709..cdd86a6 100644 --- a/Year2022/Day1.cs +++ b/Year2022/Day1.cs @@ -3,13 +3,15 @@ namespace AdventOfCode.Year2022; public class Day1 { private static readonly List CaloriesPerElf = GetCaloriesPerElf(); - + public Day1() { - Console.WriteLine("\nDay1 Solution"); - Console.WriteLine($"Part1 Result: {Part1()}"); - Console.WriteLine($"Part2 Result: {Part2()}"); - Console.WriteLine("\n=============================\n"); + Console.WriteLine($@" +Day1 Solution +Part1 Result: {Part1()} +Part2 Result: {Part2()} + +============================="); } private static int Part1() @@ -19,30 +21,21 @@ public class Day1 private static int Part2() { - List top3 = new List(); - for (int i = 0; i < 3; i++) - { - top3.Add(CaloriesPerElf.Max()); - CaloriesPerElf.Remove(CaloriesPerElf.Max()); - } - - return top3.Sum(); + return CaloriesPerElf.Order().Reverse().ToArray()[..3].Sum(); } private static List GetCaloriesPerElf() { - string[] calories = File.ReadAllLines("inputs/day1.txt"); - int[] caloriesPerDay = new int[calories.Length]; + var calories = File.ReadAllLines("inputs/day1.txt"); + var caloriesPerDay = new int[calories.Length]; var index = 0; - foreach (string calorie in calories) - { + foreach (var calorie in calories) if (calorie == "") index++; else caloriesPerDay[index] += Convert.ToInt32(calorie); - } - int elfCount = caloriesPerDay.ToList().IndexOf(0); + var elfCount = caloriesPerDay.ToList().IndexOf(0); return caloriesPerDay.ToList().GetRange(0, elfCount); } } \ No newline at end of file diff --git a/Year2022/Day10.cs b/Year2022/Day10.cs index 0906b96..d6a3e48 100644 --- a/Year2022/Day10.cs +++ b/Year2022/Day10.cs @@ -1,43 +1,44 @@ -using AdventOfCode.Utils; - namespace AdventOfCode.Year2022; public class Day10 { private static readonly List CommandsList = new(); + public Day10() { - Console.WriteLine("Day10 Solution"); File.ReadAllLines("inputs/day10.txt").ToList().ForEach(line => CommandsList.Add(line)); - - Console.WriteLine($"Part1 Result: {Part1()}"); - Console.WriteLine($"Part2 Result: {Part2()}"); - Console.WriteLine("\n=============================\n"); + Console.WriteLine($@" +Day10 Solution +Part1 Result: {Part1()} +Part2 Result: {Part2()} +============================="); } private static int Part1() { - int sum = 0; - int currentPower = 1; + var sum = 0; + var currentPower = 1; - int listIndex = 0; - int addPower = 0; - int skipCycles = 0; - - for (int cycle = 1; cycle <= 220; cycle++) + var listIndex = 0; + var addPower = 0; + var skipCycles = 0; + + for (var cycle = 1; cycle <= 220; cycle++) { if (skipCycles == 0) { currentPower += addPower; - string line = CommandsList[listIndex]; - string cmd = line.Substring(0, 4); + var line = CommandsList[listIndex]; + var cmd = line.Substring(0, 4); skipCycles = cmd == "noop" ? 0 : 1; addPower = cmd == "noop" ? 0 : Convert.ToInt32(line.Split(" ")[1]); listIndex++; } else + { skipCycles--; - + } + if ((cycle - 20) % 40 == 0) sum += currentPower * cycle; } @@ -47,37 +48,39 @@ public class Day10 private static string Part2() { - char[] crt = new char[40*6]; - int registerPos = 0; + var crt = new char[40 * 6]; + var registerPos = 0; - int listIndex = 0; - int movePos = 0; - int skipCycles = 0; - - for (int cycle = 0; cycle < 240; cycle++) + var listIndex = 0; + var movePos = 0; + var skipCycles = 0; + + for (var cycle = 0; cycle < 240; cycle++) { if (skipCycles == 0) { registerPos += movePos; - string line = CommandsList[listIndex]; - string cmd = line[..4]; + var line = CommandsList[listIndex]; + var cmd = line[..4]; skipCycles = cmd == "noop" ? 0 : 1; movePos = cmd == "noop" ? 0 : Convert.ToInt32(line.Split(" ")[1]); listIndex++; } else + { skipCycles--; + } - char[] sprite = CreateSprite(registerPos); - crt[cycle] = sprite[cycle%40]; + var sprite = CreateSprite(registerPos); + crt[cycle] = sprite[cycle % 40]; } - string result = "\n"; - int charI = 0; + var result = "\n"; + var charI = 0; crt.ToList().ForEach(c => { result += c.ToString(); - if ((charI+1)%40==0) + if ((charI + 1) % 40 == 0) result += "\n"; charI++; }); @@ -86,9 +89,9 @@ public class Day10 private static char[] CreateSprite(int registerPos) { - char[] result = new char[40]; - for (int i = 0; i < 40; i++) - result[i] = i > registerPos-1 && i < registerPos+3 ? '#' : '.'; + var result = new char[40]; + for (var i = 0; i < 40; i++) + result[i] = i > registerPos - 1 && i < registerPos + 3 ? '#' : ' '; return result; } } \ No newline at end of file diff --git a/Year2022/Day11.cs b/Year2022/Day11.cs index a1ef506..c76e818 100644 --- a/Year2022/Day11.cs +++ b/Year2022/Day11.cs @@ -9,45 +9,45 @@ public class Day11 public Day11() { - Console.WriteLine("Day11 Solution"); - File.ReadAllText("inputs/day11.txt").Split("\n\n").ToList().ForEach(monkey => { - string[] lines = monkey.Split("\n"); - + var lines = monkey.Split("\n"); + // Getting starting items - List items1 = new List(); - List items2 = new List(); + var items1 = new List(); + var items2 = new List(); lines[1][(lines[1].IndexOf(':') + 2)..].Split(", ").ToList().ForEach(item => { - items1.Add(new(Convert.ToInt32(item))); - items2.Add(new(Convert.ToInt32(item))); + items1.Add(new Item(Convert.ToInt32(item))); + items2.Add(new Item(Convert.ToInt32(item))); }); - + // Getting operation - string op = lines[2][19..]; - + var op = lines[2][19..]; + // Getting test info - int test = Convert.ToInt32(lines[3][21..]); - (int, int) testMonkeys = (Convert.ToInt32(lines[4][29..]), Convert.ToInt32(lines[5][30..])); + var test = Convert.ToInt32(lines[3][21..]); + var testMonkeys = (Convert.ToInt32(lines[4][29..]), Convert.ToInt32(lines[5][30..])); Part1Monkeys.Add(new Monkey(items1, op, test, testMonkeys)); Part2Monkeys.Add(new Monkey(items2, op, test, testMonkeys)); }); - - Console.WriteLine($"Part1 Result: {Part1()}"); - Console.WriteLine($"Part2 Result: {Part2()}"); - Console.WriteLine("\n=============================\n"); + Console.WriteLine($@" +Day11 Solution +Part1 Result: {Part1()} +Part2 Result: {Part2()} + +============================="); } private static ulong Part1() { - ulong[] inspections = new ulong[Part1Monkeys.Count]; - - for (int round = 0; round < 20; round++) - foreach (Monkey monkey in Part1Monkeys) + var inspections = new ulong[Part1Monkeys.Count]; + + for (var round = 0; round < 20; round++) + foreach (var monkey in Part1Monkeys) { - foreach (Item item in monkey.Items) + foreach (var item in monkey.Items) { if (monkey.Operation.Contains('+')) item.Value += Convert.ToInt32(monkey.Operation.Split(" ").Last()); @@ -58,11 +58,12 @@ public class Day11 item.Value /= 3; Part1Monkeys[ item.Value % monkey.DivisionTest == 0 - ? monkey.TestMonkeys.Item1 - : monkey.TestMonkeys.Item2 + ? monkey.TestMonkeys.Item1 + : monkey.TestMonkeys.Item2 ].Items.Add(item); inspections[Part1Monkeys.IndexOf(monkey)]++; } + monkey.Items.Clear(); } @@ -75,23 +76,18 @@ public class Day11 foreach (var monkey in Part2Monkeys) { monkey.UpdateItems(); - Dictionary> receiversAndItems = monkey.GetReceiversAndItems(); - foreach (int key in receiversAndItems.Keys) + var receiversAndItems = monkey.GetReceiversAndItems(); + foreach (var key in receiversAndItems.Keys) Part2Monkeys[key].ReceiveItems(receiversAndItems[key]); } - List topMonkeys = new List(); - Part2Monkeys.ForEach(monkey => topMonkeys.Add((ulong) monkey.TotalItemsChecked)); + + var topMonkeys = new List(); + Part2Monkeys.ForEach(monkey => topMonkeys.Add((ulong)monkey.TotalItemsChecked)); return topMonkeys.ProductOfMax(2); } private class Monkey { - public List Items { get; set; } - public string Operation { get; } - public int DivisionTest { get; } - public (int, int) TestMonkeys { get; } - public int TotalItemsChecked { get; private set; } - public Monkey(List items, string operation, int divisionTest, (int, int) testMonkeys) { Items = items; @@ -101,23 +97,29 @@ public class Day11 TotalItemsChecked = 0; } + public List Items { get; private set; } + public string Operation { get; } + public int DivisionTest { get; } + public (int, int) TestMonkeys { get; } + public int TotalItemsChecked { get; private set; } + public void UpdateItems() { if (Operation.Contains('+')) - foreach (Item item in Items) + foreach (var item in Items) item.UpdateDivisibleBy(Operator.Add, Convert.ToInt32(Operation.Split(" ").Last())); else if (Operation == "old * old") - foreach (Item item in Items) + foreach (var item in Items) item.UpdateDivisibleBy(Operator.Square); else - foreach (Item item in Items) + foreach (var item in Items) item.UpdateDivisibleBy(Operator.Multiply, Convert.ToInt32(Operation.Split(" ").Last())); TotalItemsChecked += Items.Count; } public Dictionary> GetReceiversAndItems() { - Dictionary> result = new Dictionary> + var result = new Dictionary> { [TestMonkeys.Item1] = new(), [TestMonkeys.Item2] = new() @@ -141,19 +143,19 @@ public class Day11 private class Item { - public int Value { get; set; } - public Dictionary DivisibleBy { get; } = new(); - public Item(int value) { Value = value; - foreach (int i in new[] { 2, 3, 5, 7, 11, 13, 17, 19, 23 }) + foreach (var i in new[] { 2, 3, 5, 7, 11, 13, 17, 19, 23 }) DivisibleBy.Add(i, value % i); } + public int Value { get; set; } + public Dictionary DivisibleBy { get; } = new(); + public void UpdateDivisibleBy(Operator op, int value = default) { - foreach (int key in DivisibleBy.Keys) + foreach (var key in DivisibleBy.Keys) DivisibleBy[key] = op switch { Operator.Add => (DivisibleBy[key] + value) % key, @@ -166,6 +168,8 @@ public class Day11 private enum Operator { - Add, Multiply, Square + Add, + Multiply, + Square } } \ No newline at end of file diff --git a/Year2022/Day2.cs b/Year2022/Day2.cs index 830ce4e..c4ec531 100644 --- a/Year2022/Day2.cs +++ b/Year2022/Day2.cs @@ -6,16 +6,18 @@ public class Day2 public Day2() { - Console.WriteLine("Day2 Solution"); - Console.WriteLine($"Part1 Result: {Part1()}"); - Console.WriteLine($"Part2 Result: {Part2()}"); - Console.WriteLine("\n=============================\n"); + Console.WriteLine($@" +Day2 Solution +Part1 Result: {Part1()} +Part2 Result: {Part2()} + +============================="); } private static int Part1() { - int score = 0; - foreach (string[] match in Matches) + var score = 0; + foreach (var match in Matches) { if (match[0] == "A") { @@ -26,6 +28,7 @@ public class Day2 if (match[1] == "Z") score += 3; } + if (match[0] == "B") { if (match[1] == "X") @@ -35,6 +38,7 @@ public class Day2 if (match[1] == "Z") score += 3 + 6; } + if (match[0] == "C") { if (match[1] == "X") @@ -51,8 +55,8 @@ public class Day2 private static int Part2() { - int score = 0; - foreach (string[] match in Matches) + var score = 0; + foreach (var match in Matches) { if (match[0] == "A") { @@ -63,6 +67,7 @@ public class Day2 if (match[1] == "Z") score += 2 + 6; } + if (match[0] == "B") { if (match[1] == "X") @@ -72,6 +77,7 @@ public class Day2 if (match[1] == "Z") score += 3 + 6; } + if (match[0] == "C") { if (match[1] == "X") @@ -88,8 +94,8 @@ public class Day2 private static List LoadMatches() { - List matches = new List(); - foreach (string line in File.ReadAllLines("inputs/day2.txt")) + var matches = new List(); + foreach (var line in File.ReadAllLines("inputs/day2.txt")) matches.Add(line.Split(" ")); return matches; } diff --git a/Year2022/Day3.cs b/Year2022/Day3.cs index b0681ef..7222e7c 100644 --- a/Year2022/Day3.cs +++ b/Year2022/Day3.cs @@ -3,58 +3,57 @@ namespace AdventOfCode.Year2022; public class Day3 { private static readonly string[] Backpacks = File.ReadAllLines("inputs/day3.txt"); - + public Day3() { - Console.WriteLine("Day3 Solution"); - Console.WriteLine($"Part1 Result: {Part1()}"); - Console.WriteLine($"Part2 Result: {Part2()}"); - Console.WriteLine("\n=============================\n"); + Console.WriteLine($@" +Day3 Solution +Part1 Result: {Part1()} +Part2 Result: {Part2()} + +============================="); } private static int Part1() { - int sum = 0; - - List duplicates = new List(); - - foreach (string backpack in Backpacks) + var sum = 0; + + var duplicates = new List(); + + foreach (var backpack in Backpacks) { - int compartmentSize = backpack.Length / 2; - List itemsInCompartment1 = new List(); - List itemsInCompartment2 = new List(); - - for (int i = 0; i < compartmentSize; i++) + var compartmentSize = backpack.Length / 2; + var itemsInCompartment1 = new List(); + var itemsInCompartment2 = new List(); + + for (var i = 0; i < compartmentSize; i++) itemsInCompartment1.Add(backpack[i]); - for (int i = compartmentSize; i < compartmentSize * 2; i++) + for (var i = compartmentSize; i < compartmentSize * 2; i++) itemsInCompartment2.Add(backpack[i]); - char duplicatedItem = itemsInCompartment1.Intersect(itemsInCompartment2).FirstOrDefault(); + var duplicatedItem = itemsInCompartment1.Intersect(itemsInCompartment2).FirstOrDefault(); duplicates.Add(duplicatedItem); } - foreach (char duplicate in duplicates) - { - if (Char.IsUpper(duplicate)) + foreach (var duplicate in duplicates) + if (char.IsUpper(duplicate)) sum += Convert.ToInt16(duplicate) - 38; else sum += Convert.ToInt16(duplicate) - 96; - } return sum; } - + private static int Part2() { - int sum = 0; - List> groups = new List>(); + var sum = 0; + var groups = new List>(); - for (int i = 0; i < Backpacks.Length; i+=3) + for (var i = 0; i < Backpacks.Length; i += 3) { - List group = new List(); + var group = new List(); - for (int x = 0; x < 3; x++) - { + for (var x = 0; x < 3; x++) try { group.Add(Backpacks[i + x]); @@ -63,26 +62,23 @@ public class Day3 { break; } - } - + if (group.All(x => x != "")) groups.Add(group); } - List duplicates = new List(); - foreach (List group in groups) + var duplicates = new List(); + foreach (var group in groups) { - string[] groupArray = group.ToArray(); + var groupArray = group.ToArray(); duplicates.Add(groupArray[0].Intersect(groupArray[1].Intersect(groupArray[2])).FirstOrDefault()); } - - foreach (char duplicate in duplicates) - { - if (Char.IsUpper(duplicate)) + + foreach (var duplicate in duplicates) + if (char.IsUpper(duplicate)) sum += Convert.ToInt16(duplicate) - 38; else sum += Convert.ToInt16(duplicate) - 96; - } return sum; } diff --git a/Year2022/Day4.cs b/Year2022/Day4.cs index 56858c2..68b14a3 100644 --- a/Year2022/Day4.cs +++ b/Year2022/Day4.cs @@ -4,47 +4,48 @@ public class Day4 { public Day4() { - Console.WriteLine("Day4 Solution"); - - string[] lines = File.ReadAllLines("inputs/day4.txt"); - int containedCount = 0; - int intersectedCount = 0; - foreach (string line in lines) + var lines = File.ReadAllLines("inputs/day4.txt"); + var containedCount = 0; + var intersectedCount = 0; + foreach (var line in lines) { if (IsContained(line)) containedCount++; if (IsIntersected(line)) intersectedCount++; } - - Console.WriteLine($"Part1 Result: {containedCount}"); - Console.WriteLine($"Part2 Result: {intersectedCount}"); - Console.WriteLine("\n=============================\n"); + + Console.WriteLine($@" +Day4 Solution +Part1 Result: {containedCount} +Part2 Result: {intersectedCount} + +============================="); } private static bool IsContained(string line) { - int[][] limits = GetLimits(line); + var limits = GetLimits(line); return (limits[0][0] >= limits[1][0] && limits[0][1] <= limits[1][1]) - || (limits[1][0] >= limits[0][0] && limits[1][1] <= limits[0][1]); + || (limits[1][0] >= limits[0][0] && limits[1][1] <= limits[0][1]); } private static bool IsIntersected(string line) { - int[][] limits = GetLimits(line); + var limits = GetLimits(line); return (limits[0][1] >= limits[1][0] && limits[0][0] <= limits[1][1]) || (limits[1][1] >= limits[0][0] && limits[1][0] <= limits[0][1]); } private static int[][] GetLimits(string line) { - string[] pair = line.Split(","); - string[] pair1 = pair[0].Split("-"); - string[] pair2 = pair[1].Split("-"); - return new [] + var pair = line.Split(","); + var pair1 = pair[0].Split("-"); + var pair2 = pair[1].Split("-"); + return new[] { - new [] {Convert.ToInt32(pair1[0]), Convert.ToInt32(pair1[1])}, - new [] {Convert.ToInt32(pair2[0]), Convert.ToInt32(pair2[1])} + new[] { Convert.ToInt32(pair1[0]), Convert.ToInt32(pair1[1]) }, + new[] { Convert.ToInt32(pair2[0]), Convert.ToInt32(pair2[1]) } }; } } \ No newline at end of file diff --git a/Year2022/Day5.cs b/Year2022/Day5.cs index 1842252..c063ee9 100644 --- a/Year2022/Day5.cs +++ b/Year2022/Day5.cs @@ -6,59 +6,59 @@ public class Day5 { private static readonly Dictionary> Crates = new() { - [1] = new(), - [2] = new(), - [3] = new(), - [4] = new(), - [5] = new(), - [6] = new(), - [7] = new(), - [8] = new(), - [9] = new() + [1] = new List(), + [2] = new List(), + [3] = new List(), + [4] = new List(), + [5] = new List(), + [6] = new List(), + [7] = new List(), + [8] = new List(), + [9] = new List() }; private static readonly List<(int, int, int)> Moves = new(); public Day5() { - Console.WriteLine("Day5 Solution"); - - string[] input = File.ReadAllText("inputs/day5.txt").Split("\n\n"); + var input = File.ReadAllText("inputs/day5.txt").Split("\n\n"); LoadCrates(input[0]); LoadMoves(input[1]); + Console.WriteLine($@" +Day5 Solution +Part1 Result: {Parts(Part.Part1)} +Part2 Result: {Parts(Part.Part2)} - Console.WriteLine($"Part1 Result: {Parts(Part.Part1)}"); - Console.WriteLine($"Part2 Result: {Parts(Part.Part2)}"); - Console.WriteLine("\n=============================\n"); +============================="); } private static string Parts(Part part) { - Dictionary> crates = Crates.Clone(); - foreach ((int, int, int) move in Moves) + var crates = Crates.Clone(); + foreach (var move in Moves) { - List cratesMoved = crates[move.Item2].Sublist(0, move.Item1); - for (int i = 0; i < move.Item1; i++) + var cratesMoved = crates[move.Item2].Sublist(0, move.Item1); + for (var i = 0; i < move.Item1; i++) crates[move.Item2].Remove(crates[move.Item2][0]); - foreach (char crate in part == Part.Part1 ? cratesMoved : cratesMoved.Reversed()) + foreach (var crate in part == Part.Part1 ? cratesMoved : cratesMoved.Reversed()) crates[move.Item3].Insert(0, crate); } - string result = ""; - foreach (List crateList in crates.Values) + var result = ""; + foreach (var crateList in crates.Values) result += crateList[0]; return result; } private static void LoadCrates(string crates) { - string[] crate_lines = crates.Split("\n"); - foreach (string line in crate_lines) + var crate_lines = crates.Split("\n"); + foreach (var line in crate_lines) { - int firstCrate = 0; + var firstCrate = 0; if (line[firstCrate] == '[') Crates[1].Add(line[1]); - while (line.Substring(firstCrate+1).Contains('[')) + while (line.Substring(firstCrate + 1).Contains('[')) { firstCrate = line.IndexOf('[', firstCrate + 1); Crates[firstCrate / 4 + 1].Add(line[firstCrate + 1]); @@ -68,18 +68,19 @@ public class Day5 private static void LoadMoves(string moves) { - string[] move_lines = moves.Split("\n"); - foreach (string line in move_lines) + var move_lines = moves.Split("\n"); + foreach (var line in move_lines) { - string move = line.Substring(5); - string[] moved = move.Split(" from "); - string[] crates = moved[1].Split(" to "); + var move = line.Substring(5); + var moved = move.Split(" from "); + var crates = moved[1].Split(" to "); Moves.Add((Convert.ToInt32(moved[0]), Convert.ToInt32(crates[0]), Convert.ToInt32(crates[1]))); } } private enum Part { - Part1, Part2 + Part1, + Part2 } } \ No newline at end of file diff --git a/Year2022/Day6.cs b/Year2022/Day6.cs index 997b663..9e18784 100644 --- a/Year2022/Day6.cs +++ b/Year2022/Day6.cs @@ -3,18 +3,20 @@ namespace AdventOfCode.Year2022; public class Day6 { private static readonly string Input = File.ReadAllText("inputs/day6.txt"); - + public Day6() { - Console.WriteLine("Day6 Solution"); - Console.WriteLine($"Part1 Result: {GetValidMarkerIndex(4)}"); - Console.WriteLine($"Part2 Result: {GetValidMarkerIndex(14)}"); - Console.WriteLine("\n=============================\n"); + Console.WriteLine($@" +Day6 Solution +Part1 Result: {GetValidMarkerIndex(4)} +Part2 Result: {GetValidMarkerIndex(14)} + +============================="); } private static int? GetValidMarkerIndex(int size) { - for (int i = 0; i < Input.Length-size; i++) + for (var i = 0; i < Input.Length - size; i++) if (ValidateMarker(Input.Substring(i, size))) return i + size; return null; diff --git a/Year2022/Day7.cs b/Year2022/Day7.cs index cfbd5c5..2ecc073 100644 --- a/Year2022/Day7.cs +++ b/Year2022/Day7.cs @@ -3,40 +3,39 @@ namespace AdventOfCode.Year2022; public class Day7 { private static readonly Dictionary> Tree = GetTree(); - + public Day7() { - Console.WriteLine("Day7 Solution"); - Console.WriteLine($"Part1 Result: {Part1()}"); - Console.WriteLine($"Part2 Result: {Part2()}"); - Console.WriteLine("\n=============================\n"); + Console.WriteLine($@" +Day7 Solution +Part1 Result: {Part1()} +Part2 Result: {Part2()} + +============================="); } private static int Part1() { - int sum = 0; - foreach (string path in Tree.Keys) + var sum = 0; + foreach (var path in Tree.Keys) { - int size = CalculateDirSize(path); + var size = CalculateDirSize(path); if (size <= 100000) sum += size; } return sum; } - + private static int Part2() { - int neededSpace = CalculateDirSize("/") - 40000000; - if (neededSpace <= 0) - { - return 0; - } + var neededSpace = CalculateDirSize("/") - 40000000; + if (neededSpace <= 0) return 0; - List bigEnoughDir = new List(); - foreach (string path in Tree.Keys) + var bigEnoughDir = new List(); + foreach (var path in Tree.Keys) { - int size = CalculateDirSize(path); + var size = CalculateDirSize(path); if (size > neededSpace) bigEnoughDir.Add(size); } @@ -47,11 +46,11 @@ public class Day7 private static int CalculateDirSize(string path) { - int size = 0; - List dirContent = Tree[path]; - foreach (string content in dirContent) + var size = 0; + var dirContent = Tree[path]; + foreach (var content in dirContent) { - string[] properties = content.Split(" "); + var properties = content.Split(" "); if (properties[0] == "dir") size += CalculateDirSize(path + properties[1] + "/"); else @@ -63,30 +62,33 @@ public class Day7 private static Dictionary> GetTree() { - Dictionary> tree = new Dictionary>(); - string currentPath = ""; + var tree = new Dictionary>(); + var currentPath = ""; - IEnumerable input = File.ReadLines("inputs/day7.txt"); - foreach (string line in input) - { + var input = File.ReadLines("inputs/day7.txt"); + foreach (var line in input) if (line.StartsWith("$")) { - string[] cmdLine = line.Substring(2).Split(" "); + var cmdLine = line.Substring(2).Split(" "); if (cmdLine[0] == "cd") { - string dir = cmdLine[1]; + var dir = cmdLine[1]; if (dir == "/") + { currentPath = "/"; + } else if (dir == "..") { if (currentPath == "/") continue; - int slashIndex = currentPath + var slashIndex = currentPath .Substring(0, currentPath.Length - 1) .LastIndexOf('/'); currentPath = currentPath.Substring(0, slashIndex + 1); } else + { currentPath += dir + "/"; + } } } else @@ -95,7 +97,6 @@ public class Day7 tree.Add(currentPath, new List()); tree[currentPath].Add(line); } - } return tree; } diff --git a/Year2022/Day8.cs b/Year2022/Day8.cs index e0a3cce..a6e2eb2 100644 --- a/Year2022/Day8.cs +++ b/Year2022/Day8.cs @@ -8,89 +8,92 @@ public class Day8 public Day8() { - Console.WriteLine("Day8 Solution"); - Console.WriteLine($"Part1 Result: {Part1()}"); - Console.WriteLine($"Part2 Result: {Part2()}"); - Console.WriteLine("\n=============================\n"); + Console.WriteLine($@" +Day8 Solution +Part1 Result: {Part1()} +Part2 Result: {Part2()} + +============================="); } private static int Part1() { - int count = 0; - for (int i = 0; i < TreeMap.Count; i++) - for (int j = 0; j < TreeMap[i].Count; j++) - if (i == 0 || i == TreeMap.Count-1 || j == 0 || j == TreeMap.Count-1 - || TreeMap[i].Sublist(0, j).Max() < TreeMap[i][j] - || TreeMap[i].Sublist(j + 1, TreeMap[i].Count).DefaultIfEmpty().Max() < TreeMap[i][j] - || TreeMap.GetColumn(j).Sublist(0, i).Max() < TreeMap[i][j] - || TreeMap.GetColumn(j).Sublist(i + 1, TreeMap[i].Count).DefaultIfEmpty().Max() < TreeMap[i][j]) - count++; + var count = 0; + for (var i = 0; i < TreeMap.Count; i++) + for (var j = 0; j < TreeMap[i].Count; j++) + if (i == 0 || i == TreeMap.Count - 1 || j == 0 || j == TreeMap.Count - 1 + || TreeMap[i].Sublist(0, j).Max() < TreeMap[i][j] + || TreeMap[i].Sublist(j + 1, TreeMap[i].Count).DefaultIfEmpty().Max() < TreeMap[i][j] + || TreeMap.GetColumn(j).Sublist(0, i).Max() < TreeMap[i][j] + || TreeMap.GetColumn(j).Sublist(i + 1, TreeMap[i].Count).DefaultIfEmpty().Max() < TreeMap[i][j]) + count++; return count; } private static int Part2() { - int highestScore = 0; + var highestScore = 0; - for (int i = 0; i < TreeMap.Count; i++) - for (int j = 0; j < TreeMap[i].Count; j++) + for (var i = 0; i < TreeMap.Count; i++) + for (var j = 0; j < TreeMap[i].Count; j++) + { + if (i == 0 || j == 0) continue; + + var currentTree = TreeMap[i][j]; + var currentTreeScore = 1; + var directionCount = 0; + + for (var k = i - 1; k >= 0; k--) { - if (i == 0 || j == 0) continue; - - int currentTree = TreeMap[i][j]; - int currentTreeScore = 1; - int directionCount = 0; - - for (int k = i - 1; k >= 0; k--) - { - directionCount++; - if (TreeMap[k][j] >= currentTree) break; - } - - currentTreeScore *= directionCount; - directionCount = 0; - - for (int k = j - 1; k >= 0; k--) - { - directionCount++; - if (TreeMap[i][k] >= currentTree) break; - } - - currentTreeScore *= directionCount; - directionCount = 0; - - for (int k = i + 1; k < TreeMap.Count; k++) - { - directionCount++; - if (TreeMap[k][j] >= currentTree) break; - } - - currentTreeScore *= directionCount; - directionCount = 0; - - for (int k = j + 1; k < TreeMap[i].Count; k++) - { - directionCount++; - if (TreeMap[i][k] >= currentTree) break; - } - - currentTreeScore *= directionCount; - highestScore = Math.Max(highestScore, currentTreeScore); + directionCount++; + if (TreeMap[k][j] >= currentTree) break; } + currentTreeScore *= directionCount; + directionCount = 0; + + for (var k = j - 1; k >= 0; k--) + { + directionCount++; + if (TreeMap[i][k] >= currentTree) break; + } + + currentTreeScore *= directionCount; + directionCount = 0; + + for (var k = i + 1; k < TreeMap.Count; k++) + { + directionCount++; + if (TreeMap[k][j] >= currentTree) break; + } + + currentTreeScore *= directionCount; + directionCount = 0; + + for (var k = j + 1; k < TreeMap[i].Count; k++) + { + directionCount++; + if (TreeMap[i][k] >= currentTree) break; + } + + currentTreeScore *= directionCount; + highestScore = Math.Max(highestScore, currentTreeScore); + } + return highestScore; } private static List> LoadMap() { - List> map = new List>(); - string[] lines = File.ReadAllLines("inputs/day8.txt"); - for (int i = 0; i < lines.Length; i++) + var map = new List>(); + var lines = File.ReadAllLines("inputs/day8.txt"); + for (var i = 0; i < lines.Length; i++) { map.Add(new List()); - for (int j = 0; j < lines[i].Length; j++) + for (var j = 0; j < lines[i].Length; j++) map[i].Add(Convert.ToInt32(lines[i][j].ToString())); } + return map; } } \ No newline at end of file diff --git a/Year2022/Day9.cs b/Year2022/Day9.cs index 33d6642..7e26152 100644 --- a/Year2022/Day9.cs +++ b/Year2022/Day9.cs @@ -6,34 +6,37 @@ public class Day9 { public Day9() { - Console.WriteLine("Day9 Solution"); - List<(char, int)> moves = new List<(char, int)>(); + var moves = new List<(char, int)>(); File.ReadAllLines("inputs/day9.txt").ToList().ForEach(line => { - string[] split = line.Split(" "); + var split = line.Split(" "); moves.Add((Convert.ToChar(split[0]), Convert.ToInt32(split[1]))); }); - Console.WriteLine($"Part1 Result: {GetPositionCount(moves, 2)}"); - Console.WriteLine($"Part2 Result: {GetPositionCount(moves, 10)}"); - Console.WriteLine("\n=============================\n"); + Console.WriteLine($@" +Day9 Solution +Part1 Result: {GetPositionCount(moves, 2)} +Part2 Result: {GetPositionCount(moves, 10)} + +============================="); } private static int GetPositionCount(List<(char, int)> moves, int knots) { - List> currentPositions = new List>(); - currentPositions.Fill(knots, new List(new[]{0,0})); - HashSet<(int, int)> tailHistory = new HashSet<(int, int)>(); + var currentPositions = new List>(); + currentPositions.Fill(knots, new List(new[] { 0, 0 })); + var tailHistory = new HashSet<(int, int)>(); - foreach ((char, int) move in moves) - for (int moveN = 0; moveN < move.Item2; moveN++) + foreach (var move in moves) + for (var moveN = 0; moveN < move.Item2; moveN++) { - int[] vector = GetVector(move.Item1); - int[] previousTailPosition = currentPositions[0].ToArray(); + var vector = GetVector(move.Item1); + var previousTailPosition = currentPositions[0].ToArray(); currentPositions[0] = UpdateHead(vector, currentPositions[0]); - for (int tailN = 0; tailN < knots-1; tailN++) + for (var tailN = 0; tailN < knots - 1; tailN++) { - int[] nextPreviousTailPosition = currentPositions[tailN + 1].ToArray(); - currentPositions[tailN + 1] = UpdateTail(currentPositions[tailN], currentPositions[tailN + 1], previousTailPosition); + var nextPreviousTailPosition = currentPositions[tailN + 1].ToArray(); + currentPositions[tailN + 1] = UpdateTail(currentPositions[tailN], currentPositions[tailN + 1], + previousTailPosition); previousTailPosition = nextPreviousTailPosition; if (tailN == knots - 2) tailHistory.Add((currentPositions[knots - 1][0], currentPositions[knots - 1][1])); @@ -50,9 +53,10 @@ public class Day9 return new List { currentPosition[0], currentPosition[1] }; } - private static List UpdateTail(List currentHeadPosition, List currentTailPosition, int[] previousTailPosition) + private static List UpdateTail(List currentHeadPosition, List currentTailPosition, + int[] previousTailPosition) { - List head = new List + var head = new List { currentHeadPosition[0] - previousTailPosition[0], currentHeadPosition[1] - previousTailPosition[1] @@ -68,8 +72,8 @@ public class Day9 currentTailPosition[0] + head[0], currentTailPosition[1] + head[1] }; - - List difference = new List + + var difference = new List { currentHeadPosition[0] - currentTailPosition[0], currentHeadPosition[1] - currentTailPosition[1] diff --git a/Year2022/Loader2022.cs b/Year2022/Loader2022.cs index 7816b55..d73b230 100644 --- a/Year2022/Loader2022.cs +++ b/Year2022/Loader2022.cs @@ -9,7 +9,7 @@ public static class Loader2022 * Solutions in C# for the 2022 Advent of Code * Slower solutions are commented */ - + new Day1(); new Day2(); new Day3(); @@ -21,5 +21,6 @@ public static class Loader2022 new Day9(); new Day10(); // new Day11(); + // new Day12(); } } \ No newline at end of file