blob: 66dcc07db5e1ca852dd8414b2bf1ab0fea64d6d2 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
//
// Created by thecharlesblake on 10/24/17.
//
#include <string>
#include <ostream>
#include <iostream>
#include <algorithm>
#include <utility>
#include "solver.h"
#include "../input-output/log_helper.h"
using namespace std;
using namespace boost;
solver::solver(const game_state& gs, const sol_rules& sr)
: initial_state(gs), rules(sr), states_searched(0) {}
solver::node::node(const game_state::move m,
vector<game_state::move> uc)
: move(m), unsearched_children(std::move(uc)) {
}
bool solver::run() {
game_state state = initial_state;
states_searched++;
LOG_DEBUG (state);
frontier.emplace_back(NULL_MOVE, state.get_legal_moves());
while (!frontier.empty()) {
node& current = frontier.back();
// If we have a solution, returns true
if (state.is_solved()) return true;
// If the current node has no unsearched children
if (current.unsearched_children.empty()) {
// Undoes the move that led to this state
// (unless it's the null first move)
if (frontier.size() > 1) {
state.undo_move(current.move);
}
// Returns to the previous state
frontier.pop_back();
} else {
game_state::move next_move = current.unsearched_children[current.unsearched_children.size()-1];
current.unsearched_children.pop_back();
// Applies the first possible move in this state
state.make_move(next_move);
// Insert the state into the global cache
bool is_new_state = global_cache.insert(state.get_data()).second;
if (is_new_state) {
states_searched++;
LOG_DEBUG (state);
// If the state is new, creates a new node in the frontier to
// represent the move just made, and those that are now possible
frontier.emplace_back(next_move, state.get_legal_moves());
} else {
// If we've seen the state before, undoes the move
state.undo_move(next_move);
}
}
}
return false;
}
void solver::print_solution() const {
std::flush(clog);
std::flush(cout);
game_state state = initial_state;
cout << "Solution:\n";
cout << state << "\n";
// Ignores first move which is
bool first = true;
for (auto f_node : frontier) {
if (first) {
first = false;
continue;
}
// TODO print move as well
state.make_move(f_node.move);
cout << state << "\n";
}
cout << "States Searched: " << states_searched << "\n";
}
|