|
| 1 | +#include <cstdlib> |
| 2 | +#include <iostream> |
| 3 | +#include <fstream> |
| 4 | +#include <vector> |
| 5 | + |
| 6 | +const int LIMIT = 2000; |
| 7 | + |
| 8 | +int next(int secret) { |
| 9 | + int mask = 16777215; // = 2^24 - 1 |
| 10 | + secret ^= secret << 6; |
| 11 | + secret &= mask; |
| 12 | + secret ^= secret >> 5; |
| 13 | + secret &= mask; |
| 14 | + secret ^= secret << 11; |
| 15 | + secret &= mask; |
| 16 | + return secret; |
| 17 | +} |
| 18 | + |
| 19 | +int prng(int secret, int n) { |
| 20 | + for (int i = 0; i < n; i++) { |
| 21 | + secret = next(secret); |
| 22 | + } |
| 23 | + return secret; |
| 24 | +} |
| 25 | + |
| 26 | +int monkey(int secret, int x1, int x2, int x3, int x4) { |
| 27 | + int d1 = -1, d2 = -1, d3 = -1, d4 = -1; |
| 28 | + for (int i = 0; i < LIMIT; i++) { |
| 29 | + int lastPrice = secret % 10; |
| 30 | + secret = next(secret); |
| 31 | + int price = secret % 10; |
| 32 | + d1 = d2; |
| 33 | + d2 = d3; |
| 34 | + d3 = d4; |
| 35 | + d4 = price - lastPrice; |
| 36 | + if (d1 == x1 && d2 == x2 && d3 == x3 && d4 == x4) { |
| 37 | + return price; |
| 38 | + } |
| 39 | + } |
| 40 | + return -1; |
| 41 | +} |
| 42 | + |
| 43 | +int score(std::vector<int> input, int x1, int x2, int x3, int x4) { |
| 44 | + int sum = 0; |
| 45 | + for (int n : input) { |
| 46 | + int price = monkey(n, x1, x2, x3, x4); |
| 47 | + if (price > 0) { |
| 48 | + sum += price; |
| 49 | + } |
| 50 | + } |
| 51 | + return sum; |
| 52 | +} |
| 53 | + |
| 54 | +int findBestScore(std::vector<int> input) { |
| 55 | + int bestScore = 0; |
| 56 | + int bound = 9; |
| 57 | + for (int x1 = -bound; x1 <= bound; x1++) { |
| 58 | + for (int x2 = -bound; x2 <= bound; x2++) { |
| 59 | + std::cout << "Searching (" << x1 << ", " << x2 << ")" << std::endl; |
| 60 | + for (int x3 = -bound; x3 <= bound; x3++) { |
| 61 | + for (int x4 = -bound; x4 <= bound; x4++) { |
| 62 | + int n = score(input, x1, x2, x3, x4); |
| 63 | + if (n > bestScore) { |
| 64 | + bestScore = n; |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + return bestScore; |
| 71 | +} |
| 72 | + |
| 73 | +int main(int argc, char *argv[]) { |
| 74 | + if (argc == 1) { |
| 75 | + std::cerr << "Usage: " << argv[0] << " <path to input>" << std::endl; |
| 76 | + return 1; |
| 77 | + } |
| 78 | + |
| 79 | + std::vector<int> input; |
| 80 | + |
| 81 | + { |
| 82 | + std::ifstream file; |
| 83 | + file.open(argv[1]); |
| 84 | + for (std::string line; std::getline(file, line);) { |
| 85 | + input.push_back(std::atoi(line.c_str())); |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + int part1 = 0; |
| 90 | + for (int n : input) { |
| 91 | + part1 += prng(n, LIMIT); |
| 92 | + } |
| 93 | + std::cout << "Part 1: " << part1 << std::endl; |
| 94 | + |
| 95 | + int part2 = findBestScore(input); |
| 96 | + std::cout << "Part 2: " << part2 << std::endl; |
| 97 | + |
| 98 | + return 0; |
| 99 | +} |
0 commit comments