From 4b6c1b0e539d9fc37b646af5865b75aaa5b49bfc Mon Sep 17 00:00:00 2001 From: Thomas Schmucker Date: Wed, 13 Nov 2024 22:20:30 +0100 Subject: aoc 2015, days 5, 6 and 7 --- 2015/src/day06.cpp | 114 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 2015/src/day06.cpp (limited to '2015/src/day06.cpp') diff --git a/2015/src/day06.cpp b/2015/src/day06.cpp new file mode 100644 index 0000000..b7f15b5 --- /dev/null +++ b/2015/src/day06.cpp @@ -0,0 +1,114 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +enum Operation { + On, + Off, + Toggle +}; + +using instruction = tuple; + +auto +read_file(string_view filename) +{ + fstream input{ filename }; + vector instructions; + + for ( string line; getline(input, line); ) { + int x0, y0, x1, y1; // NOLINT + + if ( sscanf(line.c_str(), "turn on %d,%d through %d,%d", &x0, &y0, &x1, &y1) == 4 ) { // NOLINT + instructions.emplace_back(Operation::On, x0, y0, x1, y1); + } + else if ( sscanf(line.c_str(), "toggle %d,%d through %d,%d", &x0, &y0, &x1, &y1) == 4 ) { // NOLINT + instructions.emplace_back(Operation::Toggle, x0, y0, x1, y1); + } + else if ( sscanf(line.c_str(), "turn off %d,%d through %d,%d", &x0, &y0, &x1, &y1) == 4 ) { // NOLINT + instructions.emplace_back(Operation::Off, x0, y0, x1, y1); + } + } + + return instructions; +} + +// clang-format off +static void turn_on(int& value) { value = 1; } +static void turn_off(int& value) { value = 0; } +static void toggle(int& value) { value ^= 1; } +// clang-format on + +void +part1(const vector& instructions) +{ + map> ops = { + { Operation::On, turn_on }, + { Operation::Toggle, toggle }, + { Operation::Off, turn_off } + }; + + map, int> lights; + + for ( const auto& [operation, x0, y0, x1, y1]: instructions ) { + for ( int x = x0; x <= x1; ++x ) { + for ( int y = y0; y <= y1; ++y ) { + ops[operation](lights[{ x, y }]); + } + } + } + + auto sum = count_if(begin(lights), end(lights), [](const auto& light) { + return light.second == 1; + }); + + cout << sum << endl; +} + +// clang-format off +static void increase(int& value) { ++value; } +static void decrease(int& value) { if (value > 0) { --value; } } +static void increase_by_2(int& value) { value += 2; } +// clang-format on + +void +part2(const vector& instructions) +{ + map> ops = { + { Operation::On, increase }, + { Operation::Toggle, increase_by_2 }, + { Operation::Off, decrease } + }; + + map, int> lights; + + for ( const auto& [operation, x0, y0, x1, y1]: instructions ) { + for ( int x = x0; x <= x1; ++x ) { + for ( int y = y0; y <= y1; ++y ) { + ops[operation](lights[{ x, y }]); + } + } + } + + auto sum = accumulate(begin(lights), end(lights), 0, [](int value, const auto& light) { + return value + light.second; + }); + + cout << sum << endl; +} + +int +main() +{ + auto instructions = read_file("data/day06.txt"); + part1(instructions); + part2(instructions); +} -- cgit v1.3