|
| 1 | +#include <array> |
| 2 | +#include <fstream> |
| 3 | +#include <iostream> |
| 4 | +#include <string> |
| 5 | + |
| 6 | +class CommSystem { |
| 7 | +public: |
| 8 | + void noop() { |
| 9 | + tick(); |
| 10 | + }; |
| 11 | + |
| 12 | + void addx(const int val) { |
| 13 | + tick(); |
| 14 | + tick(); |
| 15 | + X += val; |
| 16 | + } |
| 17 | + |
| 18 | + long long get_signal_strength() { |
| 19 | + return signal_strength; |
| 20 | + } |
| 21 | + |
| 22 | + void print_screen() { |
| 23 | + for(const auto& row : screen) { |
| 24 | + for (const auto ele : row) { |
| 25 | + std::cout << ele; |
| 26 | + } |
| 27 | + std::cout << '\n'; |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + |
| 32 | +private: |
| 33 | + |
| 34 | + void update_crt() { |
| 35 | + const auto pixel_id = (cycle_count - 1) % 240; |
| 36 | + const auto pixel_row = pixel_id / 40; |
| 37 | + const auto pixel_col = pixel_id % 40; |
| 38 | + // std::cout << "CRT at position: " << pixel_id << " (" << pixel_row << ',' << pixel_col << ')' << '\n'; |
| 39 | + if (pixel_col == X || pixel_col == (X - 1) || pixel_col == (X + 1)) { |
| 40 | + screen[pixel_row][pixel_col] = '#'; |
| 41 | + } else { |
| 42 | + screen[pixel_row][pixel_col] = '.'; |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + void tick() { |
| 47 | + // std::cout << "Begin cycle: " << cycle_count + 1 << '\n'; |
| 48 | + cycle_count++; |
| 49 | + update_crt(); |
| 50 | + // print_screen(); |
| 51 | + if ((cycle_count - 20) % 40 == 0) { |
| 52 | + signal_strength += cycle_count * X; |
| 53 | + } |
| 54 | + // std::cout << "End cycle: " << cycle_count << '\n'; |
| 55 | + } |
| 56 | + |
| 57 | + long long X = 1; |
| 58 | + long long cycle_count = 0; |
| 59 | + long long signal_strength = 0; |
| 60 | + std::array<std::array<char, 40>, 6> screen = {}; |
| 61 | +}; |
| 62 | + |
| 63 | + |
| 64 | +int main(int argc, char * argv[]) { |
| 65 | + std::string input = "../input/day_10_input"; |
| 66 | + if (argc > 1) { |
| 67 | + input = argv[1]; |
| 68 | + } |
| 69 | + |
| 70 | + std::string line; |
| 71 | + std::fstream file(input); |
| 72 | + |
| 73 | + CommSystem cs; |
| 74 | + |
| 75 | + while(std::getline(file, line)) { |
| 76 | + // std::cout << line << '\n'; |
| 77 | + const auto space = line.find(' '); |
| 78 | + const auto instr = line.substr(0, space); |
| 79 | + if (instr == "noop") { |
| 80 | + cs.noop(); |
| 81 | + } else if (instr == "addx") { |
| 82 | + cs.addx(std::stoi(line.substr(space + 1, line.size() - space - 1))); |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + cs.print_screen(); |
| 87 | + |
| 88 | + return 0; |
| 89 | +} |
0 commit comments