aboutsummaryrefslogtreecommitdiff
path: root/src/main/solver/solver.cpp
blob: 160af6fa9353f37a7f4597fe62c9a44766349ce6 (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
//
// Created by thecharlesblake on 10/24/17.
//

#include <string>
#include <ostream>
#include <iostream>
#include <algorithm>

#include "solver.h"
#include "input-output/log_helper.h"
#include "game/game_state.h"
#include <boost/log/trivial.hpp>

using namespace std;
using namespace boost;

solver::solver(const game_state gs, const sol_rules& sr)
        : root(NULL, gs), rules(sr), solution(root), solution_found(false),
          states_searched(0) {}

solver::node::node(const node* parent, const game_state& gs) :
        history(solver::node::gen_history(parent)), state(gs) {}

const vector<game_state> solver::node::gen_history(const node* parent) {
    vector<game_state> hist;
    if (parent != NULL) {
        hist = std::vector<game_state>(parent->history);
        hist.push_back(parent->state);
    } else {
        hist = vector<game_state>();
    }
    return hist;
}

optional<solver::node> solver::run() {
    been_run = true;

    // Iteratively run a depth-first search. Nodes in the frontier are yet to
    // be explored
    vector<node> frontier;
    frontier.push_back(root);
    while (!frontier.empty()) {
        // Pop the element at the top of the stack
        const node current = frontier.back();
        frontier.pop_back();

        LOG_DEBUG (current.state);

        // Create new nodes for each of the children
        vector<game_state> new_children = current.state.get_next_legal_states();
        states_searched++;

        // NOTE: get_next_legal_states() makes the is_solved() function work
        if (current.state.is_solved()) {
            return node(current);
        }

        for (auto it = new_children.rbegin(); it != new_children.rend(); it++) {
            // If we have seen the state before, ignore it (loop detection))
            if (find(begin(current.history), end(current.history), *it)
                != end(current.history)) {
                continue;
            }

            const node n(&current, *it);
            frontier.push_back(n);
        }
    }

    return none;
}

const solver::node solver::get_root() const {
    return root;
}

int solver::get_states_searched() const {
    return states_searched;
}

std::ostream& operator<< (std::ostream& stream, const solver::node& solution) {
    for (auto state : solution.history) {
        stream << state << "\n";
    }
    stream << solution.state << "\n";
    return stream;
}