Optimization: only simulate the relevant position.

This commit is contained in:
2019-12-28 13:58:52 +01:00
parent 649ced1515
commit c98a0bdcfd

View File

@@ -40,44 +40,27 @@ namespace {
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;
std::vector<int> deck(DECK_SIZE); int pos = 2019;
std::iota(deck.begin(), deck.end(), 0);
auto copy = deck;
for (auto move : read_moves(input)) { for (auto move : read_moves(input)) {
int argument = move.second; int argument = move.second;
int pos;
switch (move.first) { switch (move.first) {
case Operation::Stack: case Operation::Stack:
std::reverse(deck.begin(), deck.end()); pos = DECK_SIZE - 1 - pos;
break; break;
case Operation::Deal: case Operation::Deal:
pos = 0; pos = pos * argument % DECK_SIZE;
for (auto value : deck) {
copy[pos] = value;
pos = (pos + argument) % DECK_SIZE;
}
std::swap(deck, copy);
break; break;
case Operation::Cut: case Operation::Cut:
if (argument < 0) { pos = (pos - argument) % DECK_SIZE;
argument += DECK_SIZE; if (pos < 0) pos += DECK_SIZE;
}
auto it = std::copy(deck.begin() + argument, deck.end(), copy.begin());
std::copy(deck.begin(), deck.begin() + argument, it);
std::swap(deck, copy);
break; break;
} }
} }
auto location = std::find(deck.begin(), deck.end(), 2019); output << pos << std::endl;
output << std::distance(deck.begin(), location) << std::endl;
} }
void aoc2019::day22_part2(std::istream &input, std::ostream &output) { void aoc2019::day22_part2(std::istream &input, std::ostream &output) {