From d85a5ae57e20959f4dbb9b0d468e017711c8a8f7 Mon Sep 17 00:00:00 2001 From: Matthew Gretton-Dann Date: Sun, 31 Aug 2025 17:40:30 +0100 Subject: [PATCH] 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. --- main.cc | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/main.cc b/main.cc index 189ac8d..0fbde4f 100644 --- a/main.cc +++ b/main.cc @@ -130,22 +130,23 @@ auto triangle_num(int n) { return (n * (n + 1)) / 2; } using Avail = std::vector; -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); } - 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); - ++avail_sqs[idx]; - if (result) { return true; } - grid.clear(sq); - 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); + if (find_solution_impl(grid, n, grid.next_pos(pos), avail_sqs)) { return true; } + ++avail_sqs[idx]; + grid.clear(sq); + } } - 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();