82 lines
2.8 KiB
C#
82 lines
2.8 KiB
C#
namespace AdventOfCode.Solutions._2022.Day_05
|
|
{
|
|
internal class CraneWork
|
|
{
|
|
private List<Stack<char>> containerStacks = new List<Stack<char>>();
|
|
|
|
internal void ReadInitialContainerArrangement(string[] data)
|
|
{
|
|
// get all the existing stacks
|
|
string stackNumbers = data[data.Length - 1];
|
|
string[] containerStacksWithoutNumbser = data.Take(data.Length - 1).ToArray();
|
|
for (int stackIndex = 0; stackIndex < stackNumbers.Length; stackIndex++)
|
|
{
|
|
if (stackNumbers[stackIndex] == ' ')
|
|
{
|
|
continue;
|
|
}
|
|
|
|
Stack<char> stack = new Stack<char>();
|
|
for (int containerIndex = containerStacksWithoutNumbser.Length - 1; containerIndex >= 0; containerIndex--)
|
|
{
|
|
char container = containerStacksWithoutNumbser[containerIndex][stackIndex];
|
|
if (container != ' ')
|
|
{
|
|
stack.Push(container);
|
|
}
|
|
else
|
|
{
|
|
break;
|
|
}
|
|
}
|
|
|
|
containerStacks.Add(stack);
|
|
}
|
|
}
|
|
|
|
internal void DoCraneWork(string craneInstruction, bool is9000Crane = true)
|
|
{
|
|
string[] instructions = craneInstruction.Split(' ');
|
|
int numberToMove = Convert.ToInt32(instructions[1]);
|
|
|
|
// remove one because zero based index
|
|
int fromContainerStackIndex = Convert.ToInt32(instructions[3]) - 1;
|
|
int toContainerStackIndex = Convert.ToInt32(instructions[5]) - 1;
|
|
Stack<char> storage = new Stack<char>();
|
|
|
|
for (int toMove = numberToMove; toMove > 0; toMove--)
|
|
{
|
|
if (is9000Crane)
|
|
{
|
|
containerStacks[toContainerStackIndex].Push(containerStacks[fromContainerStackIndex].Pop());
|
|
}
|
|
else
|
|
{
|
|
// make a stack to store the containers in order
|
|
storage.Push(containerStacks[fromContainerStackIndex].Pop());
|
|
}
|
|
}
|
|
|
|
if (!is9000Crane)
|
|
{
|
|
// move the stored conainers to the new pile
|
|
for (int toMove = numberToMove; toMove > 0; toMove--)
|
|
{
|
|
containerStacks[toContainerStackIndex].Push(storage.Pop());
|
|
}
|
|
}
|
|
}
|
|
|
|
internal string GetTopContainers()
|
|
{
|
|
string result = string.Empty;
|
|
foreach (char topContainer in containerStacks.Select(s => s.Peek()))
|
|
{
|
|
result += topContainer;
|
|
}
|
|
|
|
return result;
|
|
}
|
|
}
|
|
}
|