Split input reading from algorithm.

This commit is contained in:
2019-12-25 17:33:18 +01:00
parent 40547cf5f8
commit 649ced1515

View File

@@ -3,6 +3,40 @@
#include "days.hpp" #include "days.hpp"
#include "utils.hpp" #include "utils.hpp"
namespace {
enum class Operation {
Stack,
Deal,
Cut
};
using Move = std::pair<Operation, int>;
std::vector<Move> read_moves(std::istream &input) {
std::string buffer;
std::vector<Move> moves;
while (std::getline(input, buffer)) {
std::string_view line = buffer;
if (!line.find("deal into new stack")) {
moves.emplace_back(Operation::Stack, 0);
} else if (!line.find("deal with increment ")) {
int new_increment;
aoc2019::from_chars(line.substr(20), new_increment);
moves.emplace_back(Operation::Deal, new_increment);
} else {
// cut
int new_offset;
aoc2019::from_chars(line.substr(4), new_offset);
moves.emplace_back(Operation::Cut, new_offset);
}
}
return moves;
}
}
void aoc2019::day22_part1(std::istream &input, std::ostream &output) { void aoc2019::day22_part1(std::istream &input, std::ostream &output) {
constexpr int DECK_SIZE = 10007; constexpr int DECK_SIZE = 10007;
@@ -11,32 +45,33 @@ void aoc2019::day22_part1(std::istream &input, std::ostream &output) {
auto copy = deck; auto copy = deck;
std::string buffer; for (auto move : read_moves(input)) {
while (std::getline(input, buffer)) { int argument = move.second;
std::string_view line = buffer; int pos;
if (!line.find("deal into new stack")) { switch (move.first) {
case Operation::Stack:
std::reverse(deck.begin(), deck.end()); std::reverse(deck.begin(), deck.end());
} else if (!line.find("deal with increment ")) { break;
int new_increment;
from_chars(line.substr(20), new_increment); case Operation::Deal:
int pos = 0; pos = 0;
for (auto value : deck) { for (auto value : deck) {
copy[pos] = value; copy[pos] = value;
pos = (pos + new_increment) % DECK_SIZE; pos = (pos + argument) % DECK_SIZE;
} }
std::swap(deck, copy); std::swap(deck, copy);
} else { break;
// cut
int new_offset; case Operation::Cut:
from_chars(line.substr(4), new_offset); if (argument < 0) {
if (new_offset < 0) { argument += DECK_SIZE;
new_offset = DECK_SIZE + new_offset;
} }
auto it = std::copy(deck.begin() + new_offset, deck.end(), copy.begin()); auto it = std::copy(deck.begin() + argument, deck.end(), copy.begin());
std::copy(deck.begin(), deck.begin() + new_offset, it); std::copy(deck.begin(), deck.begin() + argument, it);
std::swap(deck, copy); std::swap(deck, copy);
break;
} }
} }