AdventOfCode/Year2022/Day5.cs

86 lines
2.4 KiB
C#
Raw Permalink Normal View History

2023-06-11 18:36:02 +00:00
using AdventOfCode.Utils.Extensions;
2023-06-08 17:29:44 +00:00
namespace AdventOfCode.Year2022;
public class Day5
{
private static readonly Dictionary<int, List<char>> Crates = new()
{
2023-06-24 21:26:39 +00:00
[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>()
2023-06-08 17:29:44 +00:00
};
private static readonly List<(int, int, int)> Moves = new();
public Day5()
{
2023-06-24 21:26:39 +00:00
var input = File.ReadAllText("inputs/day5.txt").Split("\n\n");
2023-06-08 17:29:44 +00:00
LoadCrates(input[0]);
LoadMoves(input[1]);
2023-06-24 21:26:39 +00:00
Console.WriteLine($@"
Day5 Solution
Part1 Result: {Parts(Part.Part1)}
Part2 Result: {Parts(Part.Part2)}
2023-06-08 17:29:44 +00:00
2023-06-24 21:26:39 +00:00
=============================");
2023-06-08 17:29:44 +00:00
}
private static string Parts(Part part)
{
2023-06-24 21:26:39 +00:00
var crates = Crates.Clone();
foreach (var move in Moves)
2023-06-08 17:29:44 +00:00
{
2023-06-24 21:26:39 +00:00
var cratesMoved = crates[move.Item2].Sublist(0, move.Item1);
for (var i = 0; i < move.Item1; i++)
2023-06-08 17:29:44 +00:00
crates[move.Item2].Remove(crates[move.Item2][0]);
2023-06-24 21:26:39 +00:00
foreach (var crate in part == Part.Part1 ? cratesMoved : cratesMoved.Reversed())
2023-06-08 17:29:44 +00:00
crates[move.Item3].Insert(0, crate);
}
2023-06-24 21:26:39 +00:00
var result = "";
foreach (var crateList in crates.Values)
2023-06-08 17:29:44 +00:00
result += crateList[0];
return result;
}
private static void LoadCrates(string crates)
{
2023-06-24 21:26:39 +00:00
var crate_lines = crates.Split("\n");
foreach (var line in crate_lines)
2023-06-08 17:29:44 +00:00
{
2023-06-24 21:26:39 +00:00
var firstCrate = 0;
2023-06-08 17:29:44 +00:00
if (line[firstCrate] == '[')
Crates[1].Add(line[1]);
2023-06-24 21:26:39 +00:00
while (line.Substring(firstCrate + 1).Contains('['))
2023-06-08 17:29:44 +00:00
{
firstCrate = line.IndexOf('[', firstCrate + 1);
Crates[firstCrate / 4 + 1].Add(line[firstCrate + 1]);
}
}
}
private static void LoadMoves(string moves)
{
2023-06-24 21:26:39 +00:00
var move_lines = moves.Split("\n");
foreach (var line in move_lines)
2023-06-08 17:29:44 +00:00
{
2023-06-24 21:26:39 +00:00
var move = line.Substring(5);
var moved = move.Split(" from ");
var crates = moved[1].Split(" to ");
2023-06-08 17:29:44 +00:00
Moves.Add((Convert.ToInt32(moved[0]), Convert.ToInt32(crates[0]), Convert.ToInt32(crates[1])));
}
}
private enum Part
{
2023-06-24 21:26:39 +00:00
Part1,
Part2
2023-06-08 17:29:44 +00:00
}
}