2023 Day 16 Part 2 optimisation

We reduce the number of items we put on the list of beams to analyse.
Saving memory allocations list modifications.
This commit is contained in:
2023-12-16 09:46:46 +00:00
parent a3dc84770a
commit a40aaa9d37

View File

@@ -126,52 +126,47 @@ private:
while (!beams.empty()) { while (!beams.empty()) {
auto beam{beams.front()}; auto beam{beams.front()};
beams.pop_front(); beams.pop_front();
if (!loc_valid(beam.loc_)) { continue; } while (loc_valid(beam.loc_) && energised_.insert(beam).second) {
// Insert into hash of energised locations. If that fails we've done this before and don't switch (grid_[beam.loc_.second][beam.loc_.first]) {
// need to do it again. case '.':
if (auto [it, success] = energised_.insert(beam); !success) { continue; } break;
case '\\':
switch (grid_[beam.loc_.second][beam.loc_.first]) { if (beam.dir_ == north) { beam.dir_ = west; }
case '.': else if (beam.dir_ == east) { beam.dir_ = south; }
break; else if (beam.dir_ == south) { beam.dir_ = east; }
case '\\': else if (beam.dir_ == west) { beam.dir_ = north; }
if (beam.dir_ == north) { beam.dir_ = west; } else { std::abort(); }
else if (beam.dir_ == east) { beam.dir_ = south; } break;
else if (beam.dir_ == south) { beam.dir_ = east; } case '/':
else if (beam.dir_ == west) { beam.dir_ = north; } if (beam.dir_ == north) { beam.dir_ = east; }
else { std::abort(); } else if (beam.dir_ == east) { beam.dir_ = north; }
break; else if (beam.dir_ == south) { beam.dir_ = west; }
case '/': else if (beam.dir_ == west) { beam.dir_ = south; }
if (beam.dir_ == north) { beam.dir_ = east; } else { std::abort(); }
else if (beam.dir_ == east) { beam.dir_ = north; } break;
else if (beam.dir_ == south) { beam.dir_ = west; } case '|':
else if (beam.dir_ == west) { beam.dir_ = south; } if (beam.dir_ == east || beam.dir_ == west) {
else { std::abort(); } Beam beam2{beam};
break; beam2.dir_ = north;
case '|': beam2.loc_ = beam2.loc_ + beam2.dir_;
if (beam.dir_ == east || beam.dir_ == west) { beams.push_back(beam2);
Beam beam2{beam}; beam.dir_ = south;
beam2.dir_ = north; }
beam2.loc_ = beam2.loc_ + beam2.dir_; break;
beams.push_back(beam2); case '-':
beam.dir_ = south; if (beam.dir_ == north || beam.dir_ == south) {
Beam beam2{beam};
beam2.dir_ = east;
beam2.loc_ = beam2.loc_ + beam2.dir_;
beams.push_back(beam2);
beam.dir_ = west;
}
break;
default:
std::abort();
} }
break; beam.loc_ = beam.loc_ + beam.dir_;
case '-':
if (beam.dir_ == north || beam.dir_ == south) {
Beam beam2{beam};
beam2.dir_ = east;
beam2.loc_ = beam2.loc_ + beam2.dir_;
beams.push_back(beam2);
beam.dir_ = west;
}
break;
default:
std::abort();
} }
beam.loc_ = beam.loc_ + beam.dir_;
beams.push_back(beam);
} }
} }