--- Day 5: Supplies ---

December 5

Listening to: Christmas lo-fi


Well, whoops. I outright forgot the 5th one, so I'm doing this a day late. In my defence, I was stressing about a new job starting in the morning.


Hoo boy. Stacking crates. In a sense, the actual algorithm is simple; it's even given in the description of the problem. A bunch of stacks, and procedures for moving between them. It's trivial. The hard part is the complex parsing of the input. It's rather... graphical. It would have been easier if it was instead ZN on one line for the first stack, DCM for the second stack, and P for the third. But that would have been too easy to parse. This problem is 100% on the parsing.

So it looks like each 'box' is 3 characters long, with a space inbetween. So if I check the first character, then skip three characters until the end of the line, I'll get the contents of each box. And as long as I check that it's not empty string, I put it in a stack (rather, a deque).

while (!input.eof())
{    
    // Check for stack number line; no more parsing
    if (line[1] == '1') {
        getline(input, line);
        break;
    }

    for (int i = 0; i < line.length(); i += 4)
    {
        if (line[i+1] == ' ') continue;

        dock[i/4].push_front(line[i+1]);
    }
    
    getline(input, line);
}

Now to step through the next part, parse the 3 numbers that matter from the string, and perform the operation. All the work is in the parsing. Feilen, you were absolutely right.

int num, source, destination;
getline(input, line, ' '); // move
getline(input, line, ' '); // num
num = stoi(line); 
getline(input, line, ' '); // from
getline(input, line, ' '); // source
source = stoi(line) - 1;
getline(input, line, ' '); // to
getline(input, line     ); // destination
destination = stoi(line) - 1;

for (int i = 0; i < num; i++)
{
    dock[destination].push_back(dock[source].back());
    dock[source].pop_back();
}

Okay, interesting. Instead of moving crates one at a time, all are moved at the same time. This isn't too much more difficult. I'm just going to use an intermediary stack when moving, so the end result is the crates get put back reversed compared to part 1.

deque<char> temp;
for (int i = 0; i < num; i++)
{
    temp.push_back(dock[source].back());
    dock[source].pop_back();
}
for (int i = 0; i < num; i++)
{
    dock[destination].push_back(temp.back());
    temp.pop_back();
}

Time taken: 30 minutes (due to chatting)

My solutions for today's puzzles