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:
33
main.cc
33
main.cc
@@ -130,22 +130,23 @@ auto triangle_num(int n) { return (n * (n + 1)) / 2; }
|
|||||||
|
|
||||||
using Avail = std::vector<int>;
|
using Avail = std::vector<int>;
|
||||||
|
|
||||||
auto find_solution_impl(Grid& grid, int n, Pos const& pos, int idx, Avail& avail_sqs)-> bool {
|
auto find_solution_impl(Grid& grid, int n, Pos const& pos, Avail& avail_sqs)-> bool {
|
||||||
auto const sq = Square(pos, idx);
|
|
||||||
if (x(pos) == 0 && y(pos) == grid.length()) { return true; }
|
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 (grid.fits(sq)) {
|
if (avail_sqs[idx] == 0) { continue; }
|
||||||
--avail_sqs[idx];
|
|
||||||
grid.add(sq);
|
auto const sq = Square(pos, idx);
|
||||||
auto next_pos = grid.next_pos(pos);
|
if (grid.fits(sq)) {
|
||||||
auto const result = find_solution_impl(grid, n, next_pos, n, avail_sqs);
|
--avail_sqs[idx];
|
||||||
++avail_sqs[idx];
|
grid.add(sq);
|
||||||
if (result) { return true; }
|
if (find_solution_impl(grid, n, grid.next_pos(pos), avail_sqs)) { return true; }
|
||||||
grid.clear(sq);
|
++avail_sqs[idx];
|
||||||
return find_solution_impl(grid, n, pos, idx - 1, avail_sqs);
|
grid.clear(sq);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return find_solution_impl(grid, n, pos, idx - 1, avail_sqs);
|
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
auto find_solution(int n) -> Grid{
|
auto find_solution(int n) -> Grid{
|
||||||
@@ -153,13 +154,13 @@ auto find_solution(int n) -> Grid{
|
|||||||
Grid grid(length);
|
Grid grid(length);
|
||||||
Avail avail_sqs;
|
Avail avail_sqs;
|
||||||
for (auto i = 0; i <= n; ++i) { avail_sqs.push_back(i); }
|
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;
|
return grid;
|
||||||
}
|
}
|
||||||
|
|
||||||
int main(int argc, char** argv)
|
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);
|
auto grid = find_solution(n);
|
||||||
std::cout << "Partridge problem " << n << " side length " << grid.length() << '\n';
|
std::cout << "Partridge problem " << n << " side length " << grid.length() << '\n';
|
||||||
grid.output();
|
grid.output();
|
||||||
|
|||||||
Reference in New Issue
Block a user