parent
b0b506d60c
commit
735deb44bf
2 changed files with 87 additions and 3 deletions
@ -1,9 +1,85 @@ |
||||
#include "Day05.h" |
||||
|
||||
Result Day05::Task1() { |
||||
return Day::Task1(); |
||||
vector<Stack> stacks = parseStacks(); |
||||
const vector<Move> moves = parseMoves(); |
||||
|
||||
for (const Move &move : moves){ |
||||
int src = move.second.first; |
||||
int dest = move.second.second; |
||||
for (int i = 0; i < move.first; i++){ |
||||
stacks[dest].push_back(stacks[src].back()); |
||||
stacks[src].pop_back(); |
||||
} |
||||
} |
||||
|
||||
string result; |
||||
for (const Stack &stack : stacks) |
||||
result.push_back(stack.back()); |
||||
|
||||
return result; |
||||
} |
||||
|
||||
Result Day05::Task2() { |
||||
return Day::Task2(); |
||||
vector<Stack> stacks = parseStacks(); |
||||
const vector<Move> moves = parseMoves(); |
||||
|
||||
for (const Move &move : moves){ |
||||
int src = move.second.first; |
||||
int dest = move.second.second; |
||||
int count = move.first; |
||||
Stack &srcStack = stacks[src]; |
||||
for (int i = 0; i < count; i++){ |
||||
stacks[dest].push_back(srcStack[srcStack.size() - count + i]); |
||||
} |
||||
for (int i = 0; i < count; i++) srcStack.pop_back(); |
||||
} |
||||
|
||||
string result; |
||||
for (const Stack &stack : stacks) |
||||
result.push_back(stack.back()); |
||||
|
||||
return result; |
||||
} |
||||
|
||||
vector<Stack> Day05::parseStacks(){ |
||||
vector<Stack> parsed; |
||||
|
||||
int endIndex = splitIndex(); |
||||
string numberLine = input[endIndex - 1]; |
||||
int stackCount = atoi(&numberLine.at(numberLine.size() - 2)); |
||||
for (int i = 0; i < stackCount; i++){ |
||||
parsed.emplace_back(); |
||||
int index = 1 + 4 * i; |
||||
for (int line = endIndex - 2; line >= 0 && input[line].size() > index && input[line][index] != ' '; line--){ |
||||
Crate crate = input[line][index]; |
||||
parsed[i].push_back(crate); |
||||
} |
||||
} |
||||
|
||||
return parsed; |
||||
} |
||||
|
||||
vector<Move> Day05::parseMoves() { |
||||
vector<Move> parsed; |
||||
|
||||
int startIndex = splitIndex() + 1; |
||||
|
||||
for (int i = startIndex; i < input.size(); i++){ |
||||
string line = input[i]; |
||||
size_t fromIndex = line.find(" from"); |
||||
int count = stoi(line.substr(5, fromIndex - 5)); |
||||
int src = stoi(line.substr(fromIndex + 6, 1)) - 1; |
||||
int dest = stoi(line.substr(fromIndex + 11, 1)) - 1; |
||||
parsed.emplace_back(count, pair(src, dest)); |
||||
} |
||||
|
||||
return parsed; |
||||
} |
||||
|
||||
int Day05::splitIndex(){ |
||||
auto iter = std::find_if(input.begin(), input.end(), [](const string& element){return element == "";}); |
||||
return iter - input.begin(); |
||||
} |
||||
|
||||
|
||||
|
Loading…
Reference in new issue