aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--CMakeLists.txt13
-rw-r--r--build-notes.md7
-rw-r--r--src/main/evaluation/benchmark.cpp4
-rw-r--r--src/main/evaluation/benchmark.h2
-rw-r--r--src/main/evaluation/solvability_calc.cpp7
-rw-r--r--src/main/evaluation/solvability_calc.h3
-rw-r--r--src/main/game/global_cache.cpp117
-rw-r--r--src/main/game/global_cache.h36
-rw-r--r--src/main/game/pile.cpp4
-rw-r--r--src/main/game/search-state/game_state.legal_moves.cpp2
-rw-r--r--src/main/input-output/input/command_line_helper.cpp14
-rw-r--r--src/main/input-output/input/command_line_helper.h2
-rw-r--r--src/main/main.cpp27
-rw-r--r--src/main/solver/solver.cpp71
-rw-r--r--src/main/solver/solver.h15
-rw-r--r--src/test/test_helper.cpp2
-rw-r--r--src/test/unit_tests/global_cache_test.cpp6
17 files changed, 245 insertions, 87 deletions
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 0fcbde8..7c935f4 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,11 +1,15 @@
# File based on https://stackoverflow.com/questions/21163188/most-simple-but-complete-cmake-example
-cmake_minimum_required(VERSION 3.0)
+cmake_minimum_required(VERSION 3.9.4)
project(solvitaire)
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
+# For -flto flag
+include(CheckIPOSupported)
+check_ipo_supported(RESULT supported OUTPUT error)
+
###############################################################################
## source files ###############################################################
###############################################################################
@@ -133,10 +137,10 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14 -DBOOST_LOG_DYN_LINK -pthread
-Wcast-align -Wcast-qual -Wformat=2 -Winit-self \
-Wlogical-op -Wmissing-declarations -Wmissing-include-dirs -Wnoexcept \
-Wold-style-cast -Woverloaded-virtual -Wredundant-decls -Wshadow \
--Wstrict-null-sentinel -Werror")
+-Wstrict-null-sentinel") # -Werror
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -g")
-set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O3 -s -DNDEBUG -Wl,-O1")
-#set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O2 -g -Wl,-O1") # uncomment for profiling
+#set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O -fno-inline -fno-inline-functions -g -Wl,-O1") # uncomment for profiling
+set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O3 -flto -s -DNDEBUG -Wl,-O1") # uncomment otherwise
###############################################################################
## target definitions #########################################################
@@ -149,6 +153,7 @@ endif()
# add the data to the target, so it becomes visible in some IDE
add_executable(solvitaire ${main} ${sources})
+set_property(TARGET solvitaire PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE) # For -flto flag
target_link_libraries(solvitaire LINK_PUBLIC ${Boost_LIBRARIES})
# add a separete executable for the 'suit reduction streamliner' version of the solver
diff --git a/build-notes.md b/build-notes.md
index ae6d386..c7aca09 100644
--- a/build-notes.md
+++ b/build-notes.md
@@ -52,8 +52,5 @@ Note: this doesn't have to (and probably shouldn't) be run from within the proje
To get line numbers, you will first need to change the release build from -03 to -02
-env CPUPROFILE=solvitaire.prof CPUPROFILESIGNAL=12 CPUPROFILE_FREQUENCY=1000 cmake-build-release/bin/solvitaire --type spanish-patience --random 4 --classify &
-killall -12 solvitaire (start profiling)
-killall -12 solvitaire (stop profiling)
-pprof --callgrind src/ solvitaire.prof.0 > solvitaire.callgrind (ignore any warnings)
-kcachegrind solvitaire.callgrind
+valgrind --tool=callgrind --log-file=callgrind.log cmake-build-release/bin/solvitaire ...
+kcachegrind callgrind.out._
diff --git a/src/main/evaluation/benchmark.cpp b/src/main/evaluation/benchmark.cpp
index 42fff9d..367caf5 100644
--- a/src/main/evaluation/benchmark.cpp
+++ b/src/main/evaluation/benchmark.cpp
@@ -13,7 +13,7 @@
using namespace std;
typedef chrono::microseconds microsec;
-void benchmark::run(const sol_rules &rules) {
+void benchmark::run(const sol_rules &rules, uint64_t cache_capacity) {
cout << "Seed "
"| Median/Mean Solution Time(μs)"
"| Median/Mean States Searched "
@@ -28,7 +28,7 @@ void benchmark::run(const sol_rules &rules) {
for(int seed = 1; seed <= 1000; seed++) {
game_state gs(rules, seed);
- solver sol(gs);
+ solver sol(gs, cache_capacity);
auto start = chrono::steady_clock::now();
solver::sol_state result = sol.run();
diff --git a/src/main/evaluation/benchmark.h b/src/main/evaluation/benchmark.h
index f934bba..f8737ce 100644
--- a/src/main/evaluation/benchmark.h
+++ b/src/main/evaluation/benchmark.h
@@ -10,7 +10,7 @@
class benchmark {
public:
- static void run(const sol_rules &rules);
+ static void run(const sol_rules &rules, uint64_t);
};
diff --git a/src/main/evaluation/solvability_calc.cpp b/src/main/evaluation/solvability_calc.cpp
index 702bec3..1e650eb 100644
--- a/src/main/evaluation/solvability_calc.cpp
+++ b/src/main/evaluation/solvability_calc.cpp
@@ -17,7 +17,8 @@ using namespace std;
const double solvability_calc::coeff_ewma_weight = 0.7;
-solvability_calc::solvability_calc(const sol_rules& r) : rules(r) {
+solvability_calc::solvability_calc(const sol_rules& r, uint64_t cache_capacity_) :
+ rules(r), cache_capacity(cache_capacity_) {
}
//////////////////////
@@ -127,7 +128,7 @@ void solvability_calc::calculate_solvability_percentage() {
void solvability_calc::solve_seed(int seed, millisec timeout,
seed_results& seed_res) {
game_state gs(rules, seed);
- solver sol(gs);
+ solver sol(gs, cache_capacity);
atomic<bool> terminate_solver(false);
future<bool> future = std::async(
@@ -139,8 +140,8 @@ void solvability_calc::solve_seed(int seed, millisec timeout,
future_status status;
do {
- status = future.wait_for(timeout);
auto start = chrono::steady_clock::now();
+ status = future.wait_for(timeout);
if (status == future_status::timeout) {
terminate_solver = true;
diff --git a/src/main/evaluation/solvability_calc.h b/src/main/evaluation/solvability_calc.h
index ec9cda2..0a75e36 100644
--- a/src/main/evaluation/solvability_calc.h
+++ b/src/main/evaluation/solvability_calc.h
@@ -11,7 +11,7 @@
class solvability_calc {
public:
- explicit solvability_calc(const sol_rules&);
+ explicit solvability_calc(const sol_rules&, uint64_t);
void calculate_solvability_percentage();
@@ -63,6 +63,7 @@ private:
const sol_rules& rules;
const static double coeff_ewma_weight;
+ const uint64_t cache_capacity;
};
diff --git a/src/main/game/global_cache.cpp b/src/main/game/global_cache.cpp
index 3620ddb..db0c6de 100644
--- a/src/main/game/global_cache.cpp
+++ b/src/main/game/global_cache.cpp
@@ -7,6 +7,7 @@
#include <boost/functional/hash.hpp>
#include "global_cache.h"
+#include "../input-output/output/log_helper.h"
using namespace std;
using namespace boost;
@@ -14,12 +15,23 @@ using namespace boost;
typedef sol_rules::build_policy pol;
typedef sol_rules::stock_deal_type sdt;
+typedef boost::multi_index::multi_index_container<
+ cached_game_state,
+ boost::multi_index::indexed_by<
+ boost::multi_index::sequenced<>,
+ boost::multi_index::hashed_unique<
+ boost::multi_index::identity<cached_game_state>,
+ hasher
+ >
+ >
+> item_list;
+
///////////////////////
// CACHED GAME STATE //
///////////////////////
-cached_game_state::cached_game_state(const game_state& gs) {
+cached_game_state::cached_game_state(const game_state& gs) : live(true) {
data.reserve(52+18); // Enough for each card and up to 18 piles
if (gs.rules.hole) {
@@ -159,22 +171,107 @@ size_t hasher::hash_value(card const& c) const {
-//////////////////
+/*//////////////////
// GLOBAL CACHE //
//////////////////
-bool global_cache::insert(const game_state& gs) {
- return u_set.emplace(gs).second;
+unlimited_cache::unlimited_cache(const game_state& gs)
+ : cache(0, hasher(gs)) {
+}
+
+bool unlimited_cache::insert(const game_state& gs) {
+ return cache.emplace(gs).second;
}
-bool global_cache::contains(const game_state& gs) const {
- return u_set.count(cached_game_state(gs)) > 0;
+bool unlimited_cache::contains(const game_state& gs) const {
+ return cache.count(cached_game_state(gs)) > 0;
}
-void global_cache::clear() {
- u_set.clear();
+void unlimited_cache::clear() {
+ cache.clear();
+}*/
+
+
+///////////////
+// LRU CACHE //
+///////////////
+
+// Based on https://www.boost.org/doc/libs/1_67_0/libs/multi_index/example/serialization.cpp
+/* Boost.MultiIndex example of serialization of a MRU list.
+ *
+ * Copyright 2003-2008 Joaquin M Lopez Munoz.
+ * Distributed under the Boost Software License, Version 1.0.
+ * (See accompanying file LICENSE_1_0.txt or copy at
+ * http://www.boost.org/LICENSE_1_0.txt)
+ *
+ * See http://www.boost.org/libs/multi_index for library home page.
+ */
+
+item_list::ctor_args_list lru_cache::get_init_tuple(const game_state& gs) {
+ return boost::make_tuple(
+ item_list::nth_index<0>::type::ctor_args(),
+ boost::make_tuple(
+ size_t(0),
+ multi_index::identity<cached_game_state>(),
+ hasher(gs),
+ equal_to<cached_game_state>()
+ )
+ );
+}
+
+lru_cache::lru_cache(const game_state& gs, uint64_t max_num_items_)
+ : max_num_items(max_num_items_), cache(get_init_tuple(gs)), states_removed_from_cache(0) {
+}
+
+pair<item_list::iterator, bool> lru_cache::insert(const game_state& gs) {
+ pair<item_list::iterator, bool> p = cache.push_front(cached_game_state(gs));
+
+ if(!p.second){ /* duplicate item */
+ cache.relocate(cache.begin(), p.first); /* put in front */
+ } else if(cache.size() > max_num_items){ /* keep the length <= max_num_items */
+
+ // If the least recently used node is 'live' (i.e. a parent), relocates
+ // it to the head of the list until this is no longer the case
+ for (uint64_t i = 0; prev(cache.end())->live; i++) {
+ cache.relocate(cache.begin(), prev(cache.end()));
+
+ if (i == max_num_items) {
+ LOG_ERROR("All items in cache are live and cache is full");
+ throw runtime_error("All items in cache are live and cache is full");
+ }
+ }
+ cache.pop_back();
+ states_removed_from_cache++;
+ }
+ return p;
+}
+
+bool lru_cache::contains(const game_state& gs) const {
+ return cache.get<1>().count(cached_game_state(gs)) > 0;
+}
+
+void lru_cache::clear() {
+ cache.clear();
+}
+
+item_list::size_type lru_cache::size() const {
+ return cache.size();
+}
+
+item_list::size_type lru_cache::bucket_count() const {
+ return cache.get<1>().bucket_count();
+}
+
+void lru_cache::set_non_live(item_list::iterator state_iter) {
+#ifndef NDEBUG
+ bool succ =
+#endif
+ cache.modify(state_iter, [](auto& v){ v.live = false; });
+#ifndef NDEBUG
+ assert(succ);
+#endif
}
-global_cache::global_cache(const game_state& gs)
- : u_set(0, hasher(gs)) {
+uint64_t lru_cache::get_states_removed_from_cache() const {
+ return states_removed_from_cache;
}
diff --git a/src/main/game/global_cache.h b/src/main/game/global_cache.h
index 9541100..dd4670e 100644
--- a/src/main/game/global_cache.h
+++ b/src/main/game/global_cache.h
@@ -9,6 +9,10 @@
#include <unordered_set>
#include <boost/pool/pool.hpp>
#include <boost/pool/pool_alloc.hpp>
+#include <boost/multi_index_container.hpp>
+#include <boost/multi_index/sequenced_index.hpp>
+#include <boost/multi_index/identity.hpp>
+#include <boost/multi_index/hashed_index.hpp>
#include "sol_rules.h"
#include "search-state/game_state.h"
@@ -23,7 +27,9 @@ struct cached_game_state {
void add_card_divider();
state_data data;
+ bool live; // Is a parent in the current search tree
};
+
bool operator==(const cached_game_state&, const cached_game_state&);
struct hasher {
@@ -36,18 +42,34 @@ struct hasher {
const game_state& init_gs;
};
-class global_cache {
+class lru_cache {
public:
- explicit global_cache(const game_state&);
- bool insert(const game_state&);
+ typedef boost::multi_index::multi_index_container<
+ cached_game_state,
+ boost::multi_index::indexed_by<
+ boost::multi_index::sequenced<>,
+ boost::multi_index::hashed_unique<
+ boost::multi_index::identity<cached_game_state>,
+ hasher
+ >
+ >
+ > item_list;
+
+ explicit lru_cache(const game_state&, uint64_t);
+ std::pair<item_list::iterator, bool> insert(const game_state&);
bool contains(const game_state&) const;
void clear();
+ item_list::size_type size() const;
+ item_list::size_type bucket_count() const;
+ void set_non_live(item_list::iterator);
+ uint64_t get_states_removed_from_cache() const;
private:
- std::unordered_set<
- cached_game_state,
- hasher
- > u_set;
+ static item_list::ctor_args_list get_init_tuple(const game_state&);
+
+ uint64_t max_num_items;
+ item_list cache;
+ uint64_t states_removed_from_cache;
};
#endif //SOLVITAIRE_GLOBAL_CACHE_H
diff --git a/src/main/game/pile.cpp b/src/main/game/pile.cpp
index 3136681..23a02af 100644
--- a/src/main/game/pile.cpp
+++ b/src/main/game/pile.cpp
@@ -35,7 +35,9 @@ card& pile::operator[] (size_type i) {
}
card pile::operator[] (size_type i) const {
- return pile_vec[pile_vec.size() - 1 - i];
+ vector<card>::size_type s = pile_vec.size() - 1 - i;
+ assert(s < pile_vec.size());
+ return pile_vec[s];
}
void pile::place(const card c) {
diff --git a/src/main/game/search-state/game_state.legal_moves.cpp b/src/main/game/search-state/game_state.legal_moves.cpp
index 2acfba6..f9fc941 100644
--- a/src/main/game/search-state/game_state.legal_moves.cpp
+++ b/src/main/game/search-state/game_state.legal_moves.cpp
@@ -242,7 +242,7 @@ void game_state::add_built_group_moves(vector<move> &moves) const {
// Finds the size of the built group at the top of a pile
pile::size_type game_state::get_built_group_height(pile::ref ref) const {
pile::size_type i = 1;
- while (is_next_built_group_card(piles[ref][i], piles[ref][i-1]) && i < piles[ref].size())
+ while (i < piles[ref].size() && is_next_built_group_card(piles[ref][i], piles[ref][i-1]))
i++;
return i;
}
diff --git a/src/main/input-output/input/command_line_helper.cpp b/src/main/input-output/input/command_line_helper.cpp
index 4b0942a..e88f434 100644
--- a/src/main/input-output/input/command_line_helper.cpp
+++ b/src/main/input-output/input/command_line_helper.cpp
@@ -37,7 +37,9 @@ command_line_helper::command_line_helper()
"deal based on a seed. Must supply either 'random',"
"'solvability', 'benchmark' or list of deals to be solved.")
("classify", "outputs a simple 'solvable/not solvable' "
- "classification")
+ "classification")
+ ("cache-capacity", po::value<uint64_t>(), "sets an upper bound on the number of states allowed in "
+ "the cache")
("solvability", "calculates the solvability "
"percentage of the supplied solitaire game. Must supply "
"either 'random', 'benchmark', 'solvability' or list of deals to be "
@@ -102,6 +104,12 @@ bool command_line_helper::parse(int argc, const char* argv[]) {
random_deal = -1;
}
+ if (vm.count("cache-capacity")) {
+ cache_capacity = vm["cache-capacity"].as<uint64_t>();
+ } else {
+ cache_capacity = 100000000; // One hundred-million
+ }
+
solvability = (vm.count("solvability") != 0);
benchmark = (vm.count("benchmark") != 0);
@@ -199,6 +207,10 @@ bool command_line_helper::get_classify() {
return classify;
}
+uint64_t command_line_helper::get_cache_capacity() {
+ return cache_capacity;
+}
+
bool command_line_helper::get_solvability() {
return solvability;
}
diff --git a/src/main/input-output/input/command_line_helper.h b/src/main/input-output/input/command_line_helper.h
index 911cd5a..ca58d5f 100644
--- a/src/main/input-output/input/command_line_helper.h
+++ b/src/main/input-output/input/command_line_helper.h
@@ -20,6 +20,7 @@ public:
bool get_solvability();
bool get_available_game_types();
bool get_benchmark();
+ uint64_t get_cache_capacity();
std::string get_describe_game_rules();
private:
@@ -44,6 +45,7 @@ private:
bool solvability;
bool available_game_types;
bool benchmark;
+ uint64_t cache_capacity;
};
#endif //SOLVITAIRE_COMMAND_LINE_HELPER_H
diff --git a/src/main/main.cpp b/src/main/main.cpp
index d71db6c..8c2956d 100644
--- a/src/main/main.cpp
+++ b/src/main/main.cpp
@@ -19,9 +19,9 @@ using namespace boost;
namespace po = boost::program_options;
const optional<sol_rules> gen_rules(command_line_helper&);
-void solve_random_game(int, const sol_rules&, bool);
-void solve_input_files(vector<string>, const sol_rules&, bool);
-void solve_game(const game_state&, bool);
+void solve_random_game(int, const sol_rules&, bool, uint64_t);
+void solve_input_files(vector<string>, const sol_rules&, bool, uint64_t);
+void solve_game(const game_state&, bool, uint64_t);
// Decides what to do given supplied command-line options
int main(int argc, const char* argv[]) {
@@ -50,16 +50,16 @@ int main(int argc, const char* argv[]) {
// If the user has asked for a solvability percentage, calculates it
if (clh.get_solvability()) {
- solvability_calc solv_c(*rules);
+ solvability_calc solv_c(*rules, clh.get_cache_capacity());
solv_c.calculate_solvability_percentage();
}
// If a random deal seed has been supplied, solves it
else if (clh.get_random_deal() != -1) {
- solve_random_game(clh.get_random_deal(), *rules, clh.get_classify());
+ solve_random_game(clh.get_random_deal(), *rules, clh.get_classify(), clh.get_cache_capacity());
}
// If the benchmark option has been supplied, generates it
else if (clh.get_benchmark()) {
- benchmark::run(*rules);
+ benchmark::run(*rules, clh.get_cache_capacity());
}
// Otherwise there are supplied input files which should be solved
else {
@@ -68,7 +68,7 @@ int main(int argc, const char* argv[]) {
// If there are no input files, solve a random deal based on the
// supplied seed
assert (!input_files.empty());
- solve_input_files(input_files, *rules, clh.get_classify());
+ solve_input_files(input_files, *rules, clh.get_classify(), clh.get_cache_capacity());
}
return EXIT_SUCCESS;
@@ -90,13 +90,14 @@ const optional<sol_rules> gen_rules(command_line_helper& clh) {
}
}
-void solve_random_game(int seed, const sol_rules& rules, bool classify) {
+void solve_random_game(int seed, const sol_rules& rules, bool classify, uint64_t cache_capacity) {
LOG_INFO ("Attempting to solve with seed: " << seed << "...");
game_state gs(rules, seed);
- solve_game(gs, classify);
+ solve_game(gs, classify, cache_capacity);
}
-void solve_input_files(const vector<string> input_files, const sol_rules& rules, bool classify) {
+void solve_input_files(const vector<string> input_files, const sol_rules& rules,
+ bool classify, uint64_t cache_capacity) {
for (const string& input_file : input_files) {
try {
// Reads in the input file to a json doc
@@ -106,7 +107,7 @@ void solve_input_files(const vector<string> input_files, const sol_rules& rules,
game_state gs(rules, in_doc);
LOG_INFO ("Attempting to solve " << input_file << "...");
- solve_game(gs, classify);
+ solve_game(gs, classify, cache_capacity);
} catch (const runtime_error& error) {
string errmsg = "Error parsing deal file: ";
@@ -116,8 +117,8 @@ void solve_input_files(const vector<string> input_files, const sol_rules& rules,
}
}
-void solve_game(const game_state& gs, bool classify) {
- solver solv(gs);
+void solve_game(const game_state& gs, bool classify, uint64_t cache_capacity) {
+ solver solv(gs, cache_capacity);
bool solution = solv.run() == solver::sol_state::solved;
diff --git a/src/main/solver/solver.cpp b/src/main/solver/solver.cpp
index 7d490be..fd80556 100644
--- a/src/main/solver/solver.cpp
+++ b/src/main/solver/solver.cpp
@@ -7,6 +7,7 @@
#include <iostream>
#include <algorithm>
#include <list>
+#include <malloc.h>
#include "solver.h"
#include "../game/move.h"
@@ -16,16 +17,20 @@ using std::atomic;
using std::vector;
using std::cout;
using std::clog;
+using std::pair;
+using boost::optional;
+using std::max;
-solver::solver(const game_state& gs)
- : cache(gs)
+solver::solver(const game_state& gs, uint64_t cache_capacity)
+ : cache(lru_cache(gs, cache_capacity))
, init_state(gs)
, state(gs)
- , states_searched(1)
- , unique_states_searched(1)
+ , states_searched(0)
+ , unique_states_searched(0)
, backtracks(0)
, dominance_moves(0)
, depth(0)
+ , max_depth(0)
, root(nullptr, move(move::mtype::null))
, current_node(&root) {
}
@@ -39,8 +44,8 @@ solver::~solver() {
}
}
-solver::node::node(node* p, const move m)
- : parent(p), mv(m), children() {
+solver::node::node(node* p, const move m, optional<lru_cache::item_list::iterator> c)
+ : parent(p), mv(m), children(), parent_state_iter(c) {
}
solver::sol_state solver::run(boost::optional<atomic<bool> &> terminate_solver) {
@@ -61,22 +66,23 @@ solver::sol_state solver::run(boost::optional<atomic<bool> &> terminate_solver)
// If there is a dominance move available, adds it to the search tree
// and repeats. Doesn't cache the state.
- boost::optional<move> dominance_move = state.get_dominance_move();
+ optional<move> dominance_move = state.get_dominance_move();
if (dominance_move) {
// Adds the dominance move as a child of the current search node
add_child(*dominance_move);
} else {
// Caches the current state
- bool is_new_state = cache.insert(state);
+ pair<lru_cache::item_list::iterator, bool> insert_res = cache.insert(state);
+ bool is_new_state = insert_res.second;
if (is_new_state) {
// Gets the legal moves in the current state
- vector<move> next_moves = get_next_moves();
+ vector<move> next_moves = state.get_legal_moves(current_node->mv);
// If there are none, reverts to the last node with children
if (next_moves.empty()) {
- states_exhausted = revert_to_last_node_with_children();
+ states_exhausted = revert_to_last_node_with_children(insert_res.first);
} else {
- add_children(next_moves);
+ add_children(next_moves, insert_res.first);
}
}
// If the state is not a new one, reverts to the last node with children
@@ -92,6 +98,7 @@ solver::sol_state solver::run(boost::optional<atomic<bool> &> terminate_solver)
current_node = &current_node->children.back();
state.make_move(current_node->mv);
depth++;
+ max_depth = max(depth, max_depth);
if (current_node->mv.type == move::mtype::dominance) dominance_moves++;
}
@@ -107,28 +114,30 @@ solver::sol_state solver::run(boost::optional<atomic<bool> &> terminate_solver)
}
}
-void solver::add_children(std::vector<move>& moves) {
+void solver::add_children(std::vector<move>& moves, optional<lru_cache::item_list::iterator> i) {
current_node->children.reserve(moves.size());
for (auto move : moves) {
- add_child(move);
+ add_child(move, i);
}
}
-vector<move> solver::get_next_moves() {
- return state.get_legal_moves(current_node->mv);
-}
-
-void solver::add_child(move m) {
- current_node->children.emplace_back(current_node, m);
+void solver::add_child(move m, optional<lru_cache::item_list::iterator> i) {
+ current_node->children.emplace_back(current_node, m, i);
}
// Called when the current node's children have been exhausted. Travels back up
// the search tree until it finds a node which still has children. Returns true
// unless all children have been exhausted.
-bool solver::revert_to_last_node_with_children() {
+
+// If an iterator to the current state is supplied to the function, will also
+// make sure to turn the 'live' bit off upon backtracking
+bool solver::revert_to_last_node_with_children(optional<lru_cache::item_list::iterator> cur_state) {
if (!current_node->parent)
return true;
+ // Turns the 'live' bit false on the state we are backtracking out of
+ if (cur_state) cache.set_non_live(*cur_state);
+
state.undo_move(current_node->mv);
depth--;
backtracks++;
@@ -138,7 +147,7 @@ bool solver::revert_to_last_node_with_children() {
// (as long as the move wasn't a dominance move)
if (current_node->mv.type != move::mtype::dominance) {
- assert(cache.contains(state));
+ if (cache.get_states_removed_from_cache() == 0) assert(cache.contains(state));
LOG_DEBUG("(undo move)");
} else {
LOG_DEBUG("(undo dominance move)");
@@ -146,13 +155,17 @@ bool solver::revert_to_last_node_with_children() {
LOG_DEBUG(state);
#endif
+ // Gets a reference to the parent state which can be supplied if this function is
+ // called recursively. This ensures that the cached state's 'live' bit is set as appropriate
+ optional<lru_cache::item_list::iterator> p_state = current_node->parent_state_iter;
+
// Reverts the current node to its parent and removes it
current_node = current_node->parent;
current_node->children.pop_back();
// If the current node now has no children, repeat
if (current_node->children.empty()) {
- return revert_to_last_node_with_children();
+ return revert_to_last_node_with_children(p_state);
} else {
return false;
}
@@ -179,11 +192,15 @@ void solver::print_solution() const {
}
void solver::print_solution_info() const {
- cout << "States Searched: " << states_searched << "\n"
- << "Unique States Searched: " << unique_states_searched << "\n"
- << "Backtracks: " << backtracks << "\n"
- << "Dominance Moves: " << dominance_moves << "\n"
- << "Final Search Depth: " << depth << "\n";
+ cout << "States Searched: " << states_searched << "\n"
+ << "Unique States Searched: " << unique_states_searched << "\n"
+ << "Backtracks: " << backtracks << "\n"
+ << "Dominance Moves: " << dominance_moves << "\n"
+ << "States Removed From Cache: " << cache.get_states_removed_from_cache() << "\n"
+ << "Final States In Cache: " << cache.size() << "\n"
+ << "Final Buckets In Cache: " << cache.bucket_count() << "\n"
+ << "Maximum Search Depth: " << max_depth << "\n"
+ << "Final Search Depth: " << depth << "\n";
}
const solver::node& solver::get_search_tree() const {
diff --git a/src/main/solver/solver.h b/src/main/solver/solver.h
index 21b8d6e..bc3af0a 100644
--- a/src/main/solver/solver.h
+++ b/src/main/solver/solver.h
@@ -15,16 +15,17 @@
class solver {
public:
enum class sol_state {solved, unsolvable, timed_out};
- global_cache cache;
+ lru_cache cache;
struct node {
- node(node*, move);
+ node(node*, move, boost::optional<lru_cache::item_list::iterator> = boost::none);
node* parent;
const move mv;
std::vector<node> children;
+ boost::optional<lru_cache::item_list::iterator> parent_state_iter; // Optional, as dominance moves aren't cached
};
- explicit solver(const game_state&);
+ explicit solver(const game_state&, uint64_t);
~solver();
sol_state run(boost::optional<std::atomic<bool> &> = boost::none);
@@ -35,10 +36,9 @@ public:
const node& get_search_tree() const;
private:
- bool revert_to_last_node_with_children();
- void add_children(std::vector<move>&);
- void add_child(move);
- std::vector<move> get_next_moves();
+ bool revert_to_last_node_with_children(boost::optional<lru_cache::item_list::iterator> = boost::none);
+ void add_children(std::vector<move>&, boost::optional<lru_cache::item_list::iterator> = boost::none);
+ void add_child(move, boost::optional<lru_cache::item_list::iterator> = boost::none);
const game_state init_state;
game_state state;
@@ -48,6 +48,7 @@ private:
int backtracks;
int dominance_moves;
int depth;
+ int max_depth;
node root;
node* current_node;
diff --git a/src/test/test_helper.cpp b/src/test/test_helper.cpp
index dbc6f0d..e594c38 100644
--- a/src/test/test_helper.cpp
+++ b/src/test/test_helper.cpp
@@ -46,7 +46,7 @@ void test_helper::run_foundations_dominance_test(sol_rules::build_policy policy,
{"4D","3D","2D","AD"}
});
- solver sol = solver(game_state(gs));
+ solver sol(gs);
sol.run();
solver::node const *n = &sol.get_search_tree();
diff --git a/src/test/unit_tests/global_cache_test.cpp b/src/test/unit_tests/global_cache_test.cpp
index 6b0accd..cd3c686 100644
--- a/src/test/unit_tests/global_cache_test.cpp
+++ b/src/test/unit_tests/global_cache_test.cpp
@@ -15,7 +15,7 @@ TEST(GlobalCache, CommutativeTableauPiles) {
rules.tableau_pile_count = 3;
rules.build_pol = sol_rules::build_policy::SAME_SUIT;
game_state gs(rules, std::initializer_list<pile>{{},{},{}});
- global_cache cache(gs);
+ lru_cache cache(gs, 1000);
cache.insert (game_state(rules, {{card("AC")},{card("2D")},{card("3H")}}));
ASSERT_TRUE (cache.contains(game_state(rules, {{card("2D")},{card("3H")},{card("AC")}})));
@@ -39,7 +39,7 @@ TEST(GlobalCache, CommutativeReserve) {
rules.reserve_size = 3;
rules.build_pol = sol_rules::build_policy::SAME_SUIT;
game_state gs(rules, std::initializer_list<pile>{{},{},{}});
- global_cache cache(gs);
+ lru_cache cache(gs, 1000);
cache.insert (game_state(rules, {{card("AC")},{card("2D")},{card("3H")}}));
ASSERT_TRUE (cache.contains(game_state(rules, {{card("2D")},{card("3H")},{card("AC")}})));
@@ -63,7 +63,7 @@ TEST(GlobalCache, CommutativeCells) {
rules.cells = 3;
rules.build_pol = sol_rules::build_policy::SAME_SUIT;
game_state gs(rules, std::initializer_list<pile>{{},{},{}});
- global_cache cache(gs);
+ lru_cache cache(gs, 1000);
cache.insert (game_state(rules, {{card("AC")},{card("2D")},{card("3H")}}));
ASSERT_TRUE (cache.contains(game_state(rules, {{card("2D")},{card("3H")},{card("AC")}})));