+
+std::shared_ptr<Step> find_path(const std::string& start, const std::string& goal, unsigned max_frontier) {
+ std::istringstream iss_start{start}, iss_goal{goal};
+ Board board_start, board_goal;
+ iss_start >> board_start;
+ iss_goal >> board_goal;
+ if (iss_start.fail() || !iss_start.eof()) {
+ throw std::runtime_error("Could not parse the start board: " + start);
+ }
+ if (iss_goal.fail() || !iss_goal.eof()) {
+ throw std::runtime_error("Could not parse the goal board: " + goal);
+ }
+ return find_path(board_start, board_goal, max_frontier);
+}
+
+static void show_memory_stats() {
+ std::ifstream statm{"/proc/self/statm"};
+ if (statm.is_open()) {
+ std::string statm_data;
+ std::getline(statm, statm_data);
+ std::cerr << "Memory stats: " << statm_data << std::endl;
+ }
+}
+
+std::shared_ptr<Step> find_path(const Board& start, const Board& goal, unsigned max_frontier) {
+ InvertedBoard invgoal = goal.invert();
+ std::multimap<int, std::shared_ptr<Step>> todo;
+ std::set<Board> seen;
+
+ seen.insert(start);
+ auto start_step = std::make_shared<Step>(start, nullptr);
+ todo.emplace(start_step->cost(invgoal), start_step);
+ while (!todo.empty()) {
+ auto cur = todo.begin()->second;
+ todo.erase(todo.begin());
+ if (cur->board == goal) {
+ show_memory_stats();
+ return cur;
+ }
+ std::vector<std::shared_ptr<Step>> successors = cur->successors(cur);
+ for (const std::shared_ptr<Step>& s : successors) {
+ if (seen.find(s->board) == seen.end()) {
+ seen.insert(s->board);
+ todo.emplace(s->cost(invgoal), s);
+ if (seen.size() % 10000 == 0) {
+ std::cerr << "Examined " << seen.size() << " boards. Tracking "
+ << Step::count << " steps. " << todo.size()
+ << " waiting. Considering paths of length "
+ << cur->cost(invgoal) << std::endl;
+ }
+ }
+ }
+ while (todo.size() > max_frontier) {
+ todo.erase(--todo.end());
+ }
+ }
+ throw std::runtime_error("No path from start to goal");
+}