Change the iteration method used.

We stop using function calls to move down an index but instead use a for
 loop.

This actually provides a slight performance improvement as we are not
repeated making and destroying function frames.
This commit is contained in:
2025-08-31 17:40:30 +01:00
parent 2423f39c57
commit d85a5ae57e

23
main.cc
View File

@@ -130,22 +130,23 @@ auto triangle_num(int n) { return (n * (n + 1)) / 2; }
using Avail = std::vector<int>;
auto find_solution_impl(Grid& grid, int n, Pos const& pos, int idx, Avail& avail_sqs)-> bool {
auto const sq = Square(pos, idx);
auto find_solution_impl(Grid& grid, int n, Pos const& pos, Avail& avail_sqs)-> bool {
if (x(pos) == 0 && y(pos) == grid.length()) { return true; }
if (idx == 0) { return false; }
if (avail_sqs[idx] == 0) { return find_solution_impl(grid, n, pos, idx - 1, avail_sqs); }
for (auto idx = n; idx != 0; --idx) {
if (avail_sqs[idx] == 0) { continue; }
auto const sq = Square(pos, idx);
if (grid.fits(sq)) {
--avail_sqs[idx];
grid.add(sq);
auto next_pos = grid.next_pos(pos);
auto const result = find_solution_impl(grid, n, next_pos, n, avail_sqs);
if (find_solution_impl(grid, n, grid.next_pos(pos), avail_sqs)) { return true; }
++avail_sqs[idx];
if (result) { return true; }
grid.clear(sq);
return find_solution_impl(grid, n, pos, idx - 1, avail_sqs);
}
return find_solution_impl(grid, n, pos, idx - 1, avail_sqs);
}
return false;
}
auto find_solution(int n) -> Grid{
@@ -153,13 +154,13 @@ auto find_solution(int n) -> Grid{
Grid grid(length);
Avail avail_sqs;
for (auto i = 0; i <= n; ++i) { avail_sqs.push_back(i); }
find_solution_impl(grid, n, std::make_pair(0, 0), n, avail_sqs);
find_solution_impl(grid, n, std::make_pair(0, 0), avail_sqs);
return grid;
}
int main(int argc, char** argv)
{
auto n = (argc == 1) ? 9 : atoi(argv[1]);
auto n = (argc == 1) ? 8 : atoi(argv[1]);
auto grid = find_solution(n);
std::cout << "Partridge problem " << n << " side length " << grid.length() << '\n';
grid.output();