Some refactoring
This commit is contained in:
parent
bd026a7ff9
commit
47b55aaaec
|
@ -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)
|
||||
|
|
|
@ -3,7 +3,7 @@ namespace AdventOfCode.Utils.Extensions;
|
|||
public static class LinqExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns a slice of the given list
|
||||
/// Returns a slice of the given list
|
||||
/// </summary>
|
||||
/// <param name="list">The list you pretend to slice</param>
|
||||
/// <param name="startIndex">The first index of the slice</param>
|
||||
|
@ -11,49 +11,49 @@ public static class LinqExtensions
|
|||
/// <returns></returns>
|
||||
public static List<T> Sublist<T>(this List<T> list, int startIndex, int endIndex = default)
|
||||
{
|
||||
List<T> result = new List<T>();
|
||||
var result = new List<T>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a column of a give matrix list
|
||||
/// Returns a column of a give matrix list
|
||||
/// </summary>
|
||||
/// <param name="list">2 dimensions list</param>
|
||||
/// <param name="column">Column index</param>
|
||||
/// <returns></returns>
|
||||
public static List<T> GetColumn<T>(this List<List<T>> list, int column)
|
||||
{
|
||||
List<T> result = new List<T>();
|
||||
foreach (List<T> row in list) result.AddRange(row.Where((t, i) => i == column));
|
||||
var result = new List<T>();
|
||||
foreach (var row in list) result.AddRange(row.Where((t, i) => i == column));
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reverses a given list
|
||||
/// Reverses a given list
|
||||
/// </summary>
|
||||
/// <param name="list">The list to reverse</param>
|
||||
/// <returns>The reversed list</returns>
|
||||
public static List<T> Reversed<T>(this List<T> list)
|
||||
{
|
||||
List<T> reversed = new List<T>();
|
||||
for (int i = 0; i < list.Count; i++)
|
||||
reversed.Add(list[list.Count-1-i]);
|
||||
var reversed = new List<T>();
|
||||
for (var i = 0; i < list.Count; i++)
|
||||
reversed.Add(list[list.Count - 1 - i]);
|
||||
return reversed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clones a list of elements
|
||||
/// Clones a list of elements
|
||||
/// </summary>
|
||||
/// <param name="original">The original list</param>
|
||||
/// <returns>A copy of the original list</returns>
|
||||
public static List<T> Clone<T>(this List<T> original)
|
||||
{
|
||||
List<T> ret = new List<T>(original.Count);
|
||||
foreach (T element in original)
|
||||
var ret = new List<T>(original.Count);
|
||||
foreach (var element in original)
|
||||
ret.Add(element);
|
||||
return ret;
|
||||
}
|
||||
|
@ -63,9 +63,9 @@ public static class LinqExtensions
|
|||
where TValue : ICloneable
|
||||
where TKey : notnull
|
||||
{
|
||||
Dictionary<TKey, TValue> ret = new Dictionary<TKey, TValue>(original.Count, original.Comparer);
|
||||
foreach (KeyValuePair<TKey, TValue> entry in original)
|
||||
ret.Add(entry.Key, (TValue) entry.Value.Clone());
|
||||
var ret = new Dictionary<TKey, TValue>(original.Count, original.Comparer);
|
||||
foreach (var entry in original)
|
||||
ret.Add(entry.Key, (TValue)entry.Value.Clone());
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
@ -73,8 +73,8 @@ public static class LinqExtensions
|
|||
(this Dictionary<TKey, List<TValue>> original)
|
||||
where TKey : notnull
|
||||
{
|
||||
Dictionary<TKey, List<TValue>> ret = new Dictionary<TKey, List<TValue>>(original.Count, original.Comparer);
|
||||
foreach (KeyValuePair<TKey, List<TValue>> entry in original)
|
||||
var ret = new Dictionary<TKey, List<TValue>>(original.Count, original.Comparer);
|
||||
foreach (var entry in original)
|
||||
ret.Add(entry.Key, entry.Value.Clone());
|
||||
return ret;
|
||||
}
|
||||
|
@ -82,20 +82,20 @@ public static class LinqExtensions
|
|||
public static void Fill<T>(this List<T> list, int count, T element)
|
||||
where T : ICloneable
|
||||
{
|
||||
for (int i = 0; i < count; i++)
|
||||
for (var i = 0; i < count; i++)
|
||||
list.Add(element);
|
||||
}
|
||||
|
||||
public static void Fill<T>(this List<List<T>> list, int count, List<T> element)
|
||||
{
|
||||
for (int i = 0; i < count; i++)
|
||||
for (var i = 0; i < count; i++)
|
||||
list.Add(element.Clone());
|
||||
}
|
||||
|
||||
public static void Set<T>(this List<T> list, int index, T element)
|
||||
{
|
||||
List<T> 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]);
|
||||
}
|
||||
}
|
|
@ -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<ulong> list, int maxCount)
|
||||
{
|
||||
List<ulong> maxList = new List<ulong>(maxCount);
|
||||
var maxList = new List<ulong>(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<int> 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;
|
||||
}
|
||||
|
|
|
@ -6,10 +6,12 @@ public class Day1
|
|||
|
||||
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<int> top3 = new List<int>();
|
||||
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<int> 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);
|
||||
}
|
||||
}
|
|
@ -1,42 +1,43 @@
|
|||
using AdventOfCode.Utils;
|
||||
|
||||
namespace AdventOfCode.Year2022;
|
||||
|
||||
public class Day10
|
||||
{
|
||||
private static readonly List<string> 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;
|
||||
var listIndex = 0;
|
||||
var addPower = 0;
|
||||
var skipCycles = 0;
|
||||
|
||||
for (int cycle = 1; cycle <= 220; cycle++)
|
||||
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;
|
||||
var listIndex = 0;
|
||||
var movePos = 0;
|
||||
var skipCycles = 0;
|
||||
|
||||
for (int cycle = 0; cycle < 240; cycle++)
|
||||
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;
|
||||
}
|
||||
}
|
|
@ -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<Item> items1 = new List<Item>();
|
||||
List<Item> items2 = new List<Item>();
|
||||
var items1 = new List<Item>();
|
||||
var items2 = new List<Item>();
|
||||
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($@"
|
||||
Day11 Solution
|
||||
Part1 Result: {Part1()}
|
||||
Part2 Result: {Part2()}
|
||||
|
||||
Console.WriteLine($"Part1 Result: {Part1()}");
|
||||
Console.WriteLine($"Part2 Result: {Part2()}");
|
||||
Console.WriteLine("\n=============================\n");
|
||||
=============================");
|
||||
}
|
||||
|
||||
private static ulong Part1()
|
||||
{
|
||||
ulong[] inspections = new ulong[Part1Monkeys.Count];
|
||||
var inspections = new ulong[Part1Monkeys.Count];
|
||||
|
||||
for (int round = 0; round < 20; round++)
|
||||
foreach (Monkey monkey in Part1Monkeys)
|
||||
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<int, List<Item>> 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<ulong> topMonkeys = new List<ulong>();
|
||||
Part2Monkeys.ForEach(monkey => topMonkeys.Add((ulong) monkey.TotalItemsChecked));
|
||||
|
||||
var topMonkeys = new List<ulong>();
|
||||
Part2Monkeys.ForEach(monkey => topMonkeys.Add((ulong)monkey.TotalItemsChecked));
|
||||
return topMonkeys.ProductOfMax(2);
|
||||
}
|
||||
|
||||
private class Monkey
|
||||
{
|
||||
public List<Item> 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<Item> items, string operation, int divisionTest, (int, int) testMonkeys)
|
||||
{
|
||||
Items = items;
|
||||
|
@ -101,23 +97,29 @@ public class Day11
|
|||
TotalItemsChecked = 0;
|
||||
}
|
||||
|
||||
public List<Item> 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<int, List<Item>> GetReceiversAndItems()
|
||||
{
|
||||
Dictionary<int, List<Item>> result = new Dictionary<int, List<Item>>
|
||||
var result = new Dictionary<int, List<Item>>
|
||||
{
|
||||
[TestMonkeys.Item1] = new(),
|
||||
[TestMonkeys.Item2] = new()
|
||||
|
@ -141,19 +143,19 @@ public class Day11
|
|||
|
||||
private class Item
|
||||
{
|
||||
public int Value { get; set; }
|
||||
public Dictionary<int, int> 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<int, int> 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
|
||||
}
|
||||
}
|
|
@ -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<string[]> LoadMatches()
|
||||
{
|
||||
List<string[]> matches = new List<string[]>();
|
||||
foreach (string line in File.ReadAllLines("inputs/day2.txt"))
|
||||
var matches = new List<string[]>();
|
||||
foreach (var line in File.ReadAllLines("inputs/day2.txt"))
|
||||
matches.Add(line.Split(" "));
|
||||
return matches;
|
||||
}
|
||||
|
|
|
@ -6,55 +6,54 @@ public class Day3
|
|||
|
||||
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;
|
||||
var sum = 0;
|
||||
|
||||
List<char> duplicates = new List<char>();
|
||||
var duplicates = new List<char>();
|
||||
|
||||
foreach (string backpack in Backpacks)
|
||||
foreach (var backpack in Backpacks)
|
||||
{
|
||||
int compartmentSize = backpack.Length / 2;
|
||||
List<char> itemsInCompartment1 = new List<char>();
|
||||
List<char> itemsInCompartment2 = new List<char>();
|
||||
var compartmentSize = backpack.Length / 2;
|
||||
var itemsInCompartment1 = new List<char>();
|
||||
var itemsInCompartment2 = new List<char>();
|
||||
|
||||
for (int i = 0; i < compartmentSize; i++)
|
||||
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<List<string>> groups = new List<List<string>>();
|
||||
var sum = 0;
|
||||
var groups = new List<List<string>>();
|
||||
|
||||
for (int i = 0; i < Backpacks.Length; i+=3)
|
||||
for (var i = 0; i < Backpacks.Length; i += 3)
|
||||
{
|
||||
List<string> group = new List<string>();
|
||||
var group = new List<string>();
|
||||
|
||||
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<char> duplicates = new List<char>();
|
||||
foreach (List<string> group in groups)
|
||||
var duplicates = new List<char>();
|
||||
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;
|
||||
}
|
||||
|
|
|
@ -4,12 +4,10 @@ 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++;
|
||||
|
@ -17,34 +15,37 @@ public class Day4
|
|||
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]) }
|
||||
};
|
||||
}
|
||||
}
|
|
@ -6,59 +6,59 @@ public class Day5
|
|||
{
|
||||
private static readonly Dictionary<int, List<char>> Crates = new()
|
||||
{
|
||||
[1] = new(),
|
||||
[2] = new(),
|
||||
[3] = new(),
|
||||
[4] = new(),
|
||||
[5] = new(),
|
||||
[6] = new(),
|
||||
[7] = new(),
|
||||
[8] = new(),
|
||||
[9] = new()
|
||||
[1] = new List<char>(),
|
||||
[2] = new List<char>(),
|
||||
[3] = new List<char>(),
|
||||
[4] = new List<char>(),
|
||||
[5] = new List<char>(),
|
||||
[6] = new List<char>(),
|
||||
[7] = new List<char>(),
|
||||
[8] = new List<char>(),
|
||||
[9] = new List<char>()
|
||||
};
|
||||
|
||||
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<int, List<char>> crates = Crates.Clone();
|
||||
foreach ((int, int, int) move in Moves)
|
||||
var crates = Crates.Clone();
|
||||
foreach (var move in Moves)
|
||||
{
|
||||
List<char> 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<char> 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
|
||||
}
|
||||
}
|
|
@ -6,15 +6,17 @@ public class Day6
|
|||
|
||||
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;
|
||||
|
|
|
@ -6,18 +6,20 @@ public class Day7
|
|||
|
||||
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;
|
||||
}
|
||||
|
@ -27,16 +29,13 @@ public class Day7
|
|||
|
||||
private static int Part2()
|
||||
{
|
||||
int neededSpace = CalculateDirSize("/") - 40000000;
|
||||
if (neededSpace <= 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
var neededSpace = CalculateDirSize("/") - 40000000;
|
||||
if (neededSpace <= 0) return 0;
|
||||
|
||||
List<int> bigEnoughDir = new List<int>();
|
||||
foreach (string path in Tree.Keys)
|
||||
var bigEnoughDir = new List<int>();
|
||||
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<string> 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<string, List<string>> GetTree()
|
||||
{
|
||||
Dictionary<string, List<string>> tree = new Dictionary<string, List<string>>();
|
||||
string currentPath = "";
|
||||
var tree = new Dictionary<string, List<string>>();
|
||||
var currentPath = "";
|
||||
|
||||
IEnumerable<string> 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<string>());
|
||||
tree[currentPath].Add(line);
|
||||
}
|
||||
}
|
||||
|
||||
return tree;
|
||||
}
|
||||
|
|
125
Year2022/Day8.cs
125
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<List<int>> LoadMap()
|
||||
{
|
||||
List<List<int>> map = new List<List<int>>();
|
||||
string[] lines = File.ReadAllLines("inputs/day8.txt");
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
var map = new List<List<int>>();
|
||||
var lines = File.ReadAllLines("inputs/day8.txt");
|
||||
for (var i = 0; i < lines.Length; i++)
|
||||
{
|
||||
map.Add(new List<int>());
|
||||
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;
|
||||
}
|
||||
}
|
|
@ -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<List<int>> currentPositions = new List<List<int>>();
|
||||
currentPositions.Fill(knots, new List<int>(new[]{0,0}));
|
||||
HashSet<(int, int)> tailHistory = new HashSet<(int, int)>();
|
||||
var currentPositions = new List<List<int>>();
|
||||
currentPositions.Fill(knots, new List<int>(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<int> { currentPosition[0], currentPosition[1] };
|
||||
}
|
||||
|
||||
private static List<int> UpdateTail(List<int> currentHeadPosition, List<int> currentTailPosition, int[] previousTailPosition)
|
||||
private static List<int> UpdateTail(List<int> currentHeadPosition, List<int> currentTailPosition,
|
||||
int[] previousTailPosition)
|
||||
{
|
||||
List<int> head = new List<int>
|
||||
var head = new List<int>
|
||||
{
|
||||
currentHeadPosition[0] - previousTailPosition[0],
|
||||
currentHeadPosition[1] - previousTailPosition[1]
|
||||
|
@ -69,7 +73,7 @@ public class Day9
|
|||
currentTailPosition[1] + head[1]
|
||||
};
|
||||
|
||||
List<int> difference = new List<int>
|
||||
var difference = new List<int>
|
||||
{
|
||||
currentHeadPosition[0] - currentTailPosition[0],
|
||||
currentHeadPosition[1] - currentTailPosition[1]
|
||||
|
|
|
@ -21,5 +21,6 @@ public static class Loader2022
|
|||
new Day9();
|
||||
new Day10();
|
||||
// new Day11();
|
||||
// new Day12();
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue