Skip to content

Commit

Permalink
2023: day 16 part 2 complete (but slower than I'd like)
Browse files Browse the repository at this point in the history
  • Loading branch information
yut23 committed Dec 18, 2023
1 parent 39a83f8 commit 65a26a0
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 13 deletions.
45 changes: 39 additions & 6 deletions 2023/src/day16.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,46 @@ int main(int argc, char **argv) {
std::cerr << grid << "\n";
}

grid.send_beam();
if constexpr (aoc::DEBUG) {
grid.print_energized(std::cerr);
std::cerr << "\n";
// TODO: optimize this
// some sort of DP should work, but loops will need special handling

int max_energized = 0;
aoc::Pos pos(0, 0);
for (pos.y = 0; pos.y < grid.height(); ++pos.y) {
for (pos.x = 0; pos.x < grid.width(); pos.x += grid.width() - 1) {
aoc::AbsDirection dir =
pos.x == 0 ? aoc::AbsDirection::east : aoc::AbsDirection::west;
grid.send_beam(pos, dir);
int count = grid.count_energized();
if (pos.x == 0 && pos.y == 0) {
// part 1
if constexpr (aoc::DEBUG) {
grid.print_energized(std::cerr);
std::cerr << "\n";
}
std::cout << count << "\n";
}
if (max_energized < count) {
max_energized = count;
}
grid.clear_energized();
}
}
int part_1 = grid.count_energized();
std::cout << part_1 << "\n";

for (pos.x = 0; pos.x < grid.width(); ++pos.x) {
for (pos.y = 0; pos.y < grid.height(); pos.y += grid.height() - 1) {
aoc::AbsDirection dir = pos.y == 0 ? aoc::AbsDirection::south
: aoc::AbsDirection::north;
grid.send_beam(pos, dir);
int count = grid.count_energized();
if (max_energized < count) {
max_energized = count;
}
grid.clear_energized();
}
}

std::cout << max_energized << "\n";

return 0;
}
14 changes: 7 additions & 7 deletions 2023/src/day16.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -98,23 +98,26 @@ class Grid {
void send_beam_helper(Pos pos, AbsDirection dir, visit_cache_t &seen);

public:
void send_beam();
void send_beam(Pos pos, AbsDirection dir);
void clear_energized();
int count_energized() const;

int width() const { return tiles[0].size(); }
int height() const { return tiles.size(); }

static Grid read(std::istream &);

void print_energized(std::ostream &os) const;
friend std::ostream &operator<<(std::ostream &, const Grid &);
};

void Grid::send_beam() {
void Grid::send_beam(Pos pos, AbsDirection dir) {
visit_cache_t seen;
send_beam_helper(Pos(0, 0), AbsDirection::east, seen);
send_beam_helper(pos, dir, seen);
}

void Grid::send_beam_helper(Pos pos, AbsDirection dir, visit_cache_t &seen) {
while (true) {
while (in_bounds(pos)) {
auto key = std::make_pair(pos, dir);
if (seen.contains(key)) {
return;
Expand All @@ -130,9 +133,6 @@ void Grid::send_beam_helper(Pos pos, AbsDirection dir, visit_cache_t &seen) {
}
dir = new_dirs[0];
pos += Delta(dir, true);
if (!in_bounds(pos)) {
break;
}
}
}

Expand Down

0 comments on commit 65a26a0

Please sign in to comment.