aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--CMakeLists.txt42
-rw-r--r--benchmark.py14
-rw-r--r--src/main/game/card.cpp47
-rw-r--r--src/main/game/card.h22
-rw-r--r--src/main/game/game_state.cpp90
-rw-r--r--src/main/game/game_state.h30
-rw-r--r--src/main/game/game_state.legal_moves.cpp2
-rw-r--r--src/main/game/global_cache.cpp158
-rw-r--r--src/main/game/global_cache.h35
-rw-r--r--src/main/game/pile.cpp13
-rw-r--r--src/main/game/pile.h4
-rw-r--r--src/main/game/sol_rules.cpp29
-rw-r--r--src/main/game/sol_rules.h6
-rw-r--r--src/main/input-output/input/json-parsing/deal_parser.cpp26
-rw-r--r--src/main/input-output/input/json-parsing/deal_parser.h2
-rw-r--r--src/main/input-output/input/json-parsing/rules_parser.cpp1
-rw-r--r--src/main/input-output/output/state_printer.cpp14
-rw-r--r--src/main/main.cpp10
-rw-r--r--src/main/solver/solver.cpp12
-rw-r--r--src/main/solver/solver.h11
-rw-r--r--src/test/gloabl_cache_test.cpp102
-rw-r--r--src/test/test_helper.cpp68
-rw-r--r--src/test/test_helper.h3
23 files changed, 577 insertions, 164 deletions
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 39cd7f6..d8bae75 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -12,12 +12,33 @@ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(main src/main/main.cpp)
set(sources src/main/input-output/input/command_line_helper.cpp
- src/main/input-output/input/command_line_helper.h src/main/input-output/output/log_helper.h src/main/game/card.h
- src/main/game/card.cpp src/main/input-output/input/json-parsing/deal_parser.h src/main/input-output/input/json-parsing/deal_parser.cpp
- src/main/solver/solver.cpp src/main/solver/solver.h src/main/game/game_state.cpp
- src/main/game/game_state.h src/main/game/sol_rules.h
- src/main/game/pile.cpp src/main/game/pile.h src/main/input-output/input/json-parsing/json_helper.cpp src/main/input-output/input/json-parsing/json_helper.h src/main/input-output/input/sol_preset_types.h src/main/input-output/input/sol_preset_types.cpp src/main/input-output/input/json-parsing/rules_parser.cpp src/main/input-output/input/json-parsing/rules_parser.h src/main/input-output/output/state_printer.cpp src/main/input-output/output/state_printer.h src/main/game/game_state.legal_moves.cpp)
-set(sources_test src/test/test_helper.cpp
+ src/main/input-output/input/command_line_helper.h
+ src/main/input-output/output/log_helper.h
+ src/main/game/card.h
+ src/main/game/card.cpp
+ src/main/input-output/input/json-parsing/deal_parser.h
+ src/main/input-output/input/json-parsing/deal_parser.cpp
+ src/main/solver/solver.cpp
+ src/main/solver/solver.h
+ src/main/game/game_state.cpp
+ src/main/game/game_state.h
+ src/main/game/sol_rules.h
+ src/main/game/pile.cpp
+ src/main/game/pile.h
+ src/main/input-output/input/json-parsing/json_helper.cpp
+ src/main/input-output/input/json-parsing/json_helper.h
+ src/main/input-output/input/sol_preset_types.h
+ src/main/input-output/input/sol_preset_types.cpp
+ src/main/input-output/input/json-parsing/rules_parser.cpp
+ src/main/input-output/input/json-parsing/rules_parser.h
+ src/main/input-output/output/state_printer.cpp
+ src/main/input-output/output/state_printer.h
+ src/main/game/game_state.legal_moves.cpp
+ src/main/game/global_cache.cpp
+ src/main/game/global_cache.h
+ src/main/game/sol_rules.cpp)
+set(sources_test
+ src/test/test_helper.cpp
src/test/test_helper.h
src/test/spanish_patience_test.cpp
src/test/black_hole_test.cpp
@@ -28,7 +49,8 @@ set(sources_test src/test/test_helper.cpp
src/test/canfield_test.cpp
src/test/somerset_test.cpp
src/test/alpha_star_test.cpp
- src/test/spider_test.cpp)
+ src/test/spider_test.cpp
+ src/test/gloabl_cache_test.cpp)
###############################################################################
## Rapid JSON setup ###########################################################
@@ -108,9 +130,13 @@ endif()
# add the data to the target, so it becomes visible in some IDE
add_executable(solvitaire ${main} ${sources})
-
target_link_libraries(solvitaire LINK_PUBLIC ${Boost_LIBRARIES} -lprofiler)
+# add a separete executable for the 'simple hash' version of the solver
+add_executable(solvitaire-simple-hash ${main} ${sources})
+target_link_libraries(solvitaire-simple-hash LINK_PUBLIC ${Boost_LIBRARIES} -lprofiler)
+set_target_properties(solvitaire-simple-hash PROPERTIES COMPILE_FLAGS -DSIMPLE_HASH)
+
###############################################################################
## testing ####################################################################
diff --git a/benchmark.py b/benchmark.py
index 1eaf9f4..905d960 100644
--- a/benchmark.py
+++ b/benchmark.py
@@ -12,11 +12,17 @@ timeoutsLimit = 4
timeoutSeconds = 1
runtype = "release"
-if (len(sys.argv) == 2
+if (len(sys.argv) >= 2
and (sys.argv[1] == "--debug" or sys.argv[1] == "-d")):
runtype = "debug"
print("Running in debug mode...")
+flag = ""
+if (len(sys.argv) >= 2
+ and (sys.argv[1] == "--simple-hash" or sys.argv[1] == "-sh")):
+ flag = "-simple-hash"
+ print("Running in simple-hash mode...")
+
class SolitaireRulesGen(metaclass=ABCMeta):
def __init__(self, name):
@@ -166,8 +172,9 @@ for rulesGen in [SpanishPatienceRulesGen(),
timeouts = 0
for attempt in range(20):
try:
- run("./cmake-build-" + runtype + "/bin/solvitaire --rules "
- + tempRulesFilename + " --random " + str(attempt + 1),
+ run("./cmake-build-" + runtype + "/bin/solvitaire" + flag
+ + " --rules " + tempRulesFilename + " --random "
+ + str(attempt + 1),
shell=True,
check=True,
stdout=DEVNULL,
@@ -199,6 +206,7 @@ for rulesGen in [SpanishPatienceRulesGen(),
else:
print("Solved " + rulesGen.name + " at level " + str(level)
+ " ...")
+ summaryResults[rulesGen.name] = level
# Prints results summary table
t = PrettyTable(['Solitaire', 'Level'])
diff --git a/src/main/game/card.cpp b/src/main/game/card.cpp
index 80ebef6..5189171 100644
--- a/src/main/game/card.cpp
+++ b/src/main/game/card.cpp
@@ -20,12 +20,12 @@ card::card(const char* c) : suit(suit_from_str(c)), rank(rank_from_str(c)) {}
card::suit_t card::suit_from_str(const char* c) {
switch(tolower(c[strlen(c) - 1])) {
- case 'c': return suit_t::Clubs;
- case 'd': return suit_t::Diamonds;
- case 'h': return suit_t::Hearts;
- case 's': return suit_t::Spades;
+ case 'c': return suit::Clubs;
+ case 'h': return suit::Hearts;
+ case 's': return suit::Spades;
+ case 'd': return suit::Diamonds;
default: assert(false);
- return suit_t::Clubs;
+ return suit::Clubs;
}
}
@@ -47,9 +47,9 @@ card::suit_t card::get_suit() const {
card::colour_t card::get_colour() const {
switch (suit) {
- case card::suit_t::Spades :
- case card::suit_t::Clubs : return card::colour_t::Black;
- default : return card::colour_t::Red;
+ case card::suit::Spades :
+ case card::suit::Clubs : return card::colour::Black;
+ default : return card::colour::Red;
}
}
@@ -57,14 +57,22 @@ card::rank_t card::get_rank() const {
return rank;
}
-card::suit_t card::to_suit(uint8_t v) {
- switch (v) {
- case 0: return suit_t::Clubs;
- case 1: return suit_t::Diamonds;
- case 2: return suit_t::Hearts;
- case 3: return suit_t::Spades;
- default: assert(false); return suit_t::Clubs;
+std::string card::to_string() const {
+ string s;
+ switch(rank) {
+ case 1 : s += "A"; break;
+ case 11: s += "J"; break;
+ case 12: s += "Q"; break;
+ case 13: s += "K"; break;
+ default: s += std::to_string(rank);
}
+ switch(suit) {
+ case card::suit::Spades : s += "S"; break;
+ case card::suit::Hearts : s += "H"; break;
+ case card::suit::Clubs : s += "C"; break;
+ case card::suit::Diamonds: s += "D"; break;
+ }
+ return s;
}
bool operator==(const card& l, const card& r) {
@@ -74,12 +82,3 @@ bool operator==(const card& l, const card& r) {
bool operator!=(const card& l, const card& r) {
return !(l == r);
}
-
-size_t hash_value(card const& c) {
- boost::hash<unsigned char> hasher;
- auto raw_val = static_cast<unsigned char>(
- static_cast<std::underlying_type_t<card::suit_t>>(c.get_suit())
- * 13 + c.get_rank());
-
- return hasher(raw_val);
-} \ No newline at end of file
diff --git a/src/main/game/card.h b/src/main/game/card.h
index 4cab774..aec6a88 100644
--- a/src/main/game/card.h
+++ b/src/main/game/card.h
@@ -11,12 +11,21 @@
class card {
public:
// Types & typedefs
- enum class suit_t {Clubs, Diamonds, Hearts, Spades};
- enum class colour_t {Black, Red};
typedef uint8_t rank_t;
+ typedef uint8_t suit_t;
+ typedef uint8_t colour_t;
- // Converts a number (0-3) to a suit (Clubs-Spades)
- static suit_t to_suit(uint8_t);
+ struct suit {
+ static const suit_t Clubs = 0;
+ static const suit_t Hearts = 1;
+ static const suit_t Spades = 2;
+ static const suit_t Diamonds = 3;
+ };
+
+ struct colour {
+ static const colour_t Black = 0;
+ static const colour_t Red = 1;
+ };
// A card can either be created using two int values (rank & suit), or
// using a string (e.g. "AS")
@@ -27,17 +36,18 @@ public:
colour_t get_colour() const;
rank_t get_rank() const;
+ std::string to_string() const;
+
private:
static suit_t suit_from_str(const char* c);
static rank_t rank_from_str(const char* c);
- suit_t suit;
+ suit_t suit : 4;
rank_t rank : 4;
};
bool operator==(const card&, const card&);
bool operator!=(const card&, const card&);
-std::size_t hash_value(card const&);
#endif //SOLITAIRE_PIP_CARD_H
diff --git a/src/main/game/game_state.cpp b/src/main/game/game_state.cpp
index f8f9e1e..8075f50 100644
--- a/src/main/game/game_state.cpp
+++ b/src/main/game/game_state.cpp
@@ -14,7 +14,6 @@
#include "game_state.h"
#include "../input-output/input/json-parsing/deal_parser.h"
#include "../input-output/output/state_printer.h"
-#include "sol_rules.h"
using namespace std;
using namespace rapidjson;
@@ -23,15 +22,15 @@ using namespace boost;
typedef sol_rules::build_policy pol;
typedef sol_rules::stock_deal_type sdt;
-
//////////////////
// CONSTRUCTORS //
//////////////////
// A private constructor used by both of the public ones. Initializes all of the
// piles and pile refs specified by the rules
-game_state::game_state(const sol_rules& s_rules) :
- rules(s_rules) {
+game_state::game_state(const sol_rules& s_rules) {
+ game_state::static_reset();
+ game_state::rules = s_rules;
// If there is a hole, creates pile
if (rules.hole) {
@@ -85,14 +84,14 @@ game_state::game_state(const sol_rules& s_rules) :
}
// Constructs an initial game state from a JSON doc
-game_state::game_state(const sol_rules& s_rules, const Document& doc) :
- game_state(s_rules) {
+game_state::game_state(const sol_rules& s_rules, const Document& doc)
+ : game_state(s_rules) {
deal_parser::parse(*this, doc);
}
// Constructs an initial game state from a seed
-game_state::game_state(const sol_rules& s_rules, int seed) :
- game_state(s_rules) {
+game_state::game_state(const sol_rules& s_rules, int seed)
+ : game_state(s_rules) {
vector<card> deck = gen_shuffled_deck(seed, rules.max_rank, rules.two_decks);
// If there is a hole, moves the ace of spades to it
@@ -104,7 +103,7 @@ game_state::game_state(const sol_rules& s_rules, int seed) :
// If the foundations begin filled, then fills them
if (rules.foundations_init_card) {
for (uint8_t f_idx = 0; f_idx < 4*(rules.two_decks ? 2:1); f_idx++) {
- card c = card(card::to_suit(f_idx % uint8_t(4)), 1);
+ card c = card(f_idx % uint8_t(4), 1);
deck.erase(find(begin(deck), end(deck), c));
piles[foundations[f_idx]].place(c);
@@ -130,6 +129,9 @@ game_state::game_state(const sol_rules& s_rules, int seed) :
}
}
+ // This only occurs during testing
+ if (rules.tableau_pile_count == 0) return;
+
// Deals to the tableau piles (row-by-row)
for (int t = 0; !deck.empty(); t++) {
card c = deck.back();
@@ -163,6 +165,10 @@ game_state::game_state(const sol_rules& s_rules, int seed) :
}
}
+game_state::game_state(std::initializer_list<pile> il) {
+ piles = il;
+}
+
// Generates a randomly ordered vector of cards
vector<card> game_state::gen_shuffled_deck(int seed, card::rank_t max_rank,
bool two_decks) {
@@ -183,7 +189,7 @@ vector<card> game_state::gen_shuffled_deck(int seed, card::rank_t max_rank,
vector<card> deck;
for (uint8_t *i : v_ptrs) {
auto r = static_cast<card::rank_t>(((*i) % max_rank) + 1);
- card::suit_t s = card::to_suit((*i) / max_rank);
+ card::suit_t s = (*i) / max_rank;
deck.emplace_back(card(s, r));
}
@@ -197,6 +203,31 @@ game_state::move::move(pile_ref f, pile_ref t, pile::size_type i)
}
+////////////////////////////
+// SETUP STATIC VARIABLES //
+////////////////////////////
+
+sol_rules game_state::rules;
+std::vector<game_state::pile_ref> game_state::tableau_piles;
+std::vector<game_state::pile_ref> game_state::cells;
+game_state::pile_ref game_state::stock;
+game_state::pile_ref game_state::waste;
+std::vector<game_state::pile_ref> game_state::reserve;
+std::vector<game_state::pile_ref> game_state::foundations;
+game_state::pile_ref game_state::hole;
+
+
+void game_state::static_reset() {
+ tableau_piles.clear();
+ cells.clear();
+ stock = 0;
+ waste = 0;
+ reserve.clear();
+ foundations.clear();
+ hole = 0;
+}
+
+
/////////////////////////
// MODIFYING FUNCTIONS //
/////////////////////////
@@ -310,45 +341,6 @@ const vector<pile>& game_state::get_data() const {
return piles;
}
-bool operator==(const game_state& a, const game_state& b) {
- return a.tableau_piles == b.tableau_piles
- && a.foundations == b.foundations
- && a.hole == b.hole;
-}
-
-
-////////////////////
-// HASH FUNCTIONS //
-////////////////////
-
-size_t hash_value(game_state const& gs) {
- size_t seed = 0;
-
- if (gs.rules.foundations) {
- hash_combine(seed, gs.foundations);
- }
- if (gs.rules.cells) {
- hash_combine(seed, gs.cells);
- }
- if (gs.rules.tableau_pile_count > 0) {
- hash_combine(seed, gs.tableau_piles);
- }
-
- if (gs.rules.stock_size > 0) {
- hash_combine(seed, gs.piles[gs.stock]);
- hash_combine(seed, gs.piles[gs.waste]);
- }
- if (gs.rules.hole) {
- hash_combine(seed, gs.piles[gs.hole]);
- }
-
- return seed;
-}
-
-size_t hash_value(vector<pile> const& vp) {
- return hash_range(begin(vp), end(vp));
-}
-
///////////
// PRINT //
diff --git a/src/main/game/game_state.h b/src/main/game/game_state.h
index 323646f..8dcffa4 100644
--- a/src/main/game/game_state.h
+++ b/src/main/game/game_state.h
@@ -15,11 +15,10 @@
#include "pile.h"
#include "sol_rules.h"
-class deal_parser;
-
class game_state {
friend class deal_parser;
friend class state_printer;
+ friend class game_state_pred;
public:
// Defines types
typedef uint8_t pile_ref;
@@ -34,6 +33,9 @@ public:
// Does the same from a 'rules' object
game_state(const sol_rules&, int seed);
+ // For testing
+ game_state(std::initializer_list<pile>);
+
// Alters state
void make_move(move);
void undo_move(move);
@@ -44,14 +46,13 @@ public:
bool is_solved() const;
const std::vector<pile>& get_data() const;
- friend bool operator==(const game_state&, const game_state&);
+ friend std::ostream& operator<< (std::ostream&, const game_state&);
+ friend std::size_t hash_value(card const&);
friend std::size_t hash_value(game_state const&);
- friend std::size_t hash_value(std::vector<pile> const&);
-
- friend std::ostream& operator<< (std::ostream&, const game_state&);
private:
+ void static_reset();
static std::vector<card> gen_shuffled_deck(int, card::rank_t, bool);
// Private constructor
@@ -70,18 +71,17 @@ private:
card) const;
// References to piles
- sol_rules rules;
- std::vector<pile_ref> tableau_piles;
- std::vector<pile_ref> cells;
- pile_ref stock;
- pile_ref waste;
- std::vector<pile_ref> reserve;
- std::vector<pile_ref> foundations;
- pile_ref hole;
+ static sol_rules rules;
+ static std::vector<pile_ref> tableau_piles;
+ static std::vector<pile_ref> cells;
+ static pile_ref stock;
+ static pile_ref waste;
+ static std::vector<pile_ref> reserve;
+ static std::vector<pile_ref> foundations;
+ static pile_ref hole;
// The core piles
std::vector<pile> piles;
};
-
#endif //SOLVITAIRE_GAME_STATE_H
diff --git a/src/main/game/game_state.legal_moves.cpp b/src/main/game/game_state.legal_moves.cpp
index 7dfc87c..3043587 100644
--- a/src/main/game/game_state.legal_moves.cpp
+++ b/src/main/game/game_state.legal_moves.cpp
@@ -128,7 +128,7 @@ bool game_state::is_valid_foundations_move(const pile_ref rem_ref,
// Checks violation of same suit policy
uint8_t suit_idx = (add_ref - foundations.front()) % uint8_t(4);
- if (rem_c.get_suit() != card::to_suit(suit_idx)) {
+ if (rem_c.get_suit() != suit_idx) {
return false;
}
diff --git a/src/main/game/global_cache.cpp b/src/main/game/global_cache.cpp
new file mode 100644
index 0000000..8e3aa8b
--- /dev/null
+++ b/src/main/game/global_cache.cpp
@@ -0,0 +1,158 @@
+//
+// Created by thecharlesblake on 1/10/18.
+//
+
+#include <algorithm>
+
+#include "global_cache.h"
+
+using namespace std;
+using namespace boost;
+
+typedef sol_rules::build_policy pol;
+typedef sol_rules::stock_deal_type sdt;
+
+bool global_cache::insert(const game_state& gs) {
+ return u_set.insert(gs).second;
+}
+
+bool global_cache::contains(const game_state& gs) const {
+ return u_set.count(gs) > 0;
+}
+
+void global_cache::clear() {
+ u_set.clear();
+}
+
+size_t hash_value(card const& c) {
+ boost::hash<uint8_t> hasher;
+
+#ifdef SIMPLE_HASH
+ uint8_t suit_val = static_cast<uint8_t>(c.get_suit());
+#else
+ uint8_t suit_val;
+ switch (game_state::rules.build_pol) {
+ case pol::SAME_SUIT:
+ suit_val = static_cast<uint8_t>(c.get_suit());
+ break;
+ case pol::RED_BLACK:
+ suit_val = static_cast<uint8_t>(c.get_colour());
+ break;
+ default:
+ suit_val = 0;
+ }
+#endif
+
+ auto raw_val = static_cast<uint8_t>(suit_val * 13 + c.get_rank());
+ return hasher(raw_val);
+}
+
+size_t hash_value(pile const& p) {
+ return hash_range(begin(p.pile_vec), end(p.pile_vec));
+}
+
+size_t hash_value(game_state const& gs) {
+ size_t seed = 0;
+
+#ifdef SIMPLE_HASH
+ for (game_state::pile_ref pr = 0; pr < gs.piles.size(); pr++) {
+ hash_combine(seed, gs.piles[pr]);
+ }
+#else
+ boost::hash<pile> pile_hasher;
+
+ // Using addition for commutative hash
+ for (game_state::pile_ref pr : game_state::tableau_piles) {
+ seed += pile_hasher(gs.piles[pr]);
+ }
+
+ // Using hash_combine for order-dependent hash
+ for (game_state::pile_ref pr : game_state::foundations) {
+ hash_combine(seed, gs.piles[pr]);
+ }
+
+ // Commutative
+ for (game_state::pile_ref pr : game_state::reserve) {
+ seed += pile_hasher(gs.piles[pr]);
+ }
+
+ if (game_state::rules.stock_size > 0) {
+ hash_combine(seed, gs.piles[game_state::stock]);
+ }
+
+ if (game_state::rules.stock_deal_t == sdt::WASTE) {
+ hash_combine(seed, gs.piles[game_state::waste]);
+ }
+
+ if (game_state::rules.hole) {
+ hash_combine(seed, gs.piles[game_state::hole]);
+ }
+
+ // Commutative
+ for (game_state::pile_ref pr : game_state::cells) {
+ seed += pile_hasher(gs.piles[pr]);
+ }
+#endif
+
+ return seed;
+}
+
+bool game_state_pred::comp_pile(const pile &x, const pile &y) {
+ // Largest piles first
+ if (x.size() != y.size()) {
+ return x.size() > y.size();
+ }
+ // Larger card values first
+ for (pile::size_type pile_idx = 0; pile_idx < x.size(); pile_idx++) {
+ auto x_val = static_cast<uint8_t>(x[pile_idx].get_suit()) * 13
+ + x[pile_idx].get_rank();
+ auto y_val = static_cast<uint8_t>(y[pile_idx].get_suit()) * 13
+ + y[pile_idx].get_rank();
+ if (x_val != y_val) {
+ return x_val > y_val;
+ }
+ }
+ // It is a requirement of std::sort that equal values return false
+ return false;
+}
+
+bool game_state_pred::operator()(const game_state& x,
+ const game_state& y) const {
+ if (x.piles.size() != y.piles.size()) return false;
+
+ vector<pile> x_piles = x.piles;
+ vector<pile> y_piles = y.piles;
+
+ // Orders the piles from largest to smallest
+ sort(begin(x_piles), end(x_piles), comp_pile);
+ sort(begin(y_piles), end(y_piles), comp_pile);
+
+ // Compares the two for equality
+ for (vector<pile>::size_type pile_idx = 0; pile_idx < x_piles.size(); pile_idx++) {
+ if (x_piles[pile_idx].size() != y_piles[pile_idx].size()) return false;
+
+ for (auto card_idx = 0; card_idx < x_piles[pile_idx].size(); card_idx++) {
+ card cx = x_piles[pile_idx][card_idx];
+ card cy = y_piles[pile_idx][card_idx];
+
+ if (cx.get_rank() != cy.get_rank()) return false;
+
+#ifdef SIMPLE_HASH
+ if (cx.get_suit() != cy.get_suit()) return false;
+#else
+ switch (game_state::rules.build_pol) {
+ case pol::SAME_SUIT:
+ if (cx.get_suit() != cy.get_suit()) return false;
+ break;
+ case pol::RED_BLACK:
+ if (cx.get_colour() != cy.get_colour()) return false;
+ break;
+ default:
+ break;
+ }
+#endif
+ }
+ }
+
+ return true;
+}
diff --git a/src/main/game/global_cache.h b/src/main/game/global_cache.h
new file mode 100644
index 0000000..486006c
--- /dev/null
+++ b/src/main/game/global_cache.h
@@ -0,0 +1,35 @@
+//
+// Created by thecharlesblake on 1/10/18.
+//
+
+#ifndef SOLVITAIRE_GLOBAL_CACHE_H
+#define SOLVITAIRE_GLOBAL_CACHE_H
+
+#include <vector>
+#include <unordered_set>
+
+#include <boost/functional/hash.hpp>
+
+#include "sol_rules.h"
+#include "game_state.h"
+
+struct game_state_pred {
+ static bool comp_pile(const pile& x, const pile& y);
+ bool operator() (const game_state& x, const game_state& y)
+ const;
+};
+
+class global_cache {
+public:
+ bool insert(const game_state&);
+ bool contains(const game_state&) const;
+ void clear();
+private:
+ std::unordered_set<
+ game_state,
+ boost::hash<game_state>,
+ game_state_pred
+ > u_set;
+};
+
+#endif //SOLVITAIRE_GLOBAL_CACHE_H
diff --git a/src/main/game/pile.cpp b/src/main/game/pile.cpp
index 82ae344..21eddc0 100644
--- a/src/main/game/pile.cpp
+++ b/src/main/game/pile.cpp
@@ -5,12 +5,15 @@
#include <vector>
#include <ostream>
-#include <boost/functional/hash.hpp>
-
#include "pile.h"
using namespace std;
-using namespace boost;
+
+pile::pile(std::vector<card> pv) : pile_vec(pv) {
+}
+
+pile::pile(std::initializer_list<card> il) : pile_vec(il) {
+}
card pile::top_card() const {
assert(!empty());
@@ -47,7 +50,3 @@ card pile::take() {
bool operator==(const pile& a, const pile& b) {
return a.pile_vec == b.pile_vec;
}
-
-size_t hash_value(pile const& p) {
- return hash_range(begin(p.pile_vec), end(p.pile_vec));
-}
diff --git a/src/main/game/pile.h b/src/main/game/pile.h
index f2600fe..411f890 100644
--- a/src/main/game/pile.h
+++ b/src/main/game/pile.h
@@ -15,6 +15,10 @@ class pile {
public:
typedef uint8_t size_type;
+ pile() = default;
+ pile(std::vector<card>);
+ pile(std::initializer_list<card>);
+
// Inspect
card top_card() const;
bool empty() const;
diff --git a/src/main/game/sol_rules.cpp b/src/main/game/sol_rules.cpp
new file mode 100644
index 0000000..7311e06
--- /dev/null
+++ b/src/main/game/sol_rules.cpp
@@ -0,0 +1,29 @@
+//
+// Created by thecharlesblake on 1/12/18.
+//
+
+#include "sol_rules.h"
+
+typedef sol_rules::build_policy pol;
+typedef sol_rules::spaces_policy s_pol;
+typedef sol_rules::stock_deal_type sdt;
+
+// Note that the 'default' sol rules are set up by parsing the default json
+// rules description. This initialisation is really just for testing purposes.
+sol_rules::sol_rules() :
+ tableau_pile_count(0),
+ build_pol(pol::ANY_SUIT),
+ spaces_pol(s_pol::ANY),
+ move_built_group(false),
+ two_decks(false),
+ max_rank(13),
+ hole(false),
+ foundations(false),
+ foundations_init_card(false),
+ diagonal_deal(false),
+ cells(0),
+ stock_size(0),
+ stock_deal_t(sdt::TABLEAU_PILES),
+ reserve_size(0),
+ reserve_stacked(false) {
+}
diff --git a/src/main/game/sol_rules.h b/src/main/game/sol_rules.h
index 812e82c..067e107 100644
--- a/src/main/game/sol_rules.h
+++ b/src/main/game/sol_rules.h
@@ -9,9 +9,9 @@
#include <rapidjson/document.h>
-#include "card.h"
-
struct sol_rules {
+ sol_rules();
+
// Tableau policies
enum class build_policy {
NO_BUILD,
@@ -33,7 +33,7 @@ struct sol_rules {
spaces_policy spaces_pol;
bool move_built_group;
bool two_decks;
- card::rank_t max_rank;
+ uint8_t max_rank;
bool hole;
bool foundations;
bool foundations_init_card;
diff --git a/src/main/input-output/input/json-parsing/deal_parser.cpp b/src/main/input-output/input/json-parsing/deal_parser.cpp
index b2a4c9d..7cf5f45 100644
--- a/src/main/input-output/input/json-parsing/deal_parser.cpp
+++ b/src/main/input-output/input/json-parsing/deal_parser.cpp
@@ -13,32 +13,32 @@ typedef sol_rules::build_policy pol;
void deal_parser::parse(game_state &gs, const rapidjson::Document& doc) {
// Construct tableau piles
- if (gs.rules.tableau_pile_count > 0) {
+ if (game_state::rules.tableau_pile_count > 0) {
parse_tableau_piles(gs, doc);
}
// Construct hole card
- if (gs.rules.hole) {
+ if (game_state::rules.hole) {
parse_hole(gs, doc);
}
// Construct filled cells
- if (gs.rules.cells) {
+ if (game_state::rules.cells) {
parse_cells(gs, doc);
}
// Construct stock
- if (gs.rules.stock_size > 0) {
+ if (game_state::rules.stock_size > 0) {
parse_stock(gs, doc);
}
// Construct reserve
- if (gs.rules.reserve_size > 0) {
+ if (game_state::rules.reserve_size > 0) {
parse_reserve(gs, doc);
}
// If the foundations begin with cards in them, fill them
- if (gs.rules.foundations_init_card) {
+ if (game_state::rules.foundations_init_card) {
fill_foundations(gs);
}
}
@@ -48,7 +48,7 @@ void deal_parser::parse_tableau_piles(game_state &gs, const rapidjson::Document&
const Value& json_tab_piles = doc["tableau piles"];
assert(json_tab_piles.IsArray());
- if (json_tab_piles.Size() != gs.rules.tableau_pile_count ) {
+ if (json_tab_piles.Size() != game_state::rules.tableau_pile_count ) {
json_helper::json_parse_err("Incorrect number of tableau piles");
}
@@ -81,7 +81,7 @@ void deal_parser::parse_cells(game_state &gs, const Document& doc) {
const auto json_cell_arr = json_cells.GetArray();
if (json_cell_arr.Empty()) return;
- else if (json_cell_arr.Size() != gs.rules.cells) {
+ else if (json_cell_arr.Size() != game_state::rules.cells) {
json_helper::json_parse_err("Incorrect number of cells");
}
@@ -101,7 +101,7 @@ void deal_parser::parse_stock(game_state &gs, const Document& doc) {
const Value &json_stock = doc["stock"];
assert(json_stock.IsArray());
- if (json_stock.Size() != gs.rules.stock_size) {
+ if (json_stock.Size() != game_state::rules.stock_size) {
json_helper::json_parse_err("Incorrect stock size");
}
@@ -121,25 +121,25 @@ void deal_parser::parse_reserve(game_state &gs, const Document& doc) {
// We treat a regular reserve like multiple single-card piles,
// but a stacked reserve as a single multiple-card pile
- if (json_reserve_piles.Size() != gs.rules.reserve_size) {
+ if (json_reserve_piles.Size() != game_state::rules.reserve_size) {
json_helper::json_parse_err("Incorrect reserve size");
}
for (game_state::pile_ref i = 0; i < json_card_arr.Size(); i++) {
assert(json_card_arr[i].IsString());
game_state::pile_ref pr = gs.reserve[0];
- if (!gs.rules.reserve_stacked) pr += i;
+ if (!game_state::rules.reserve_stacked) pr += i;
gs.piles[pr].place(card(json_card_arr[i].GetString()));
}
}
void deal_parser::fill_foundations(game_state &gs) {
- auto foundations_count = uint8_t(4 * (gs.rules.two_decks ? 2:1));
+ auto foundations_count = uint8_t(4 * (game_state::rules.two_decks ? 2:1));
assert(gs.foundations.size() == foundations_count);
for (uint8_t f_idx = 0; f_idx < foundations_count; f_idx++) {
gs.piles[gs.foundations[f_idx]].place(
- card(card::to_suit(f_idx % uint8_t(4)), 1)
+ card(f_idx % uint8_t(4), 1)
);
}
}
diff --git a/src/main/input-output/input/json-parsing/deal_parser.h b/src/main/input-output/input/json-parsing/deal_parser.h
index ecb596c..98916cd 100644
--- a/src/main/input-output/input/json-parsing/deal_parser.h
+++ b/src/main/input-output/input/json-parsing/deal_parser.h
@@ -11,8 +11,6 @@
#include <rapidjson/document.h>
#include <rapidjson/schema.h>
-#include "../../../game/sol_rules.h"
-
class game_state;
class deal_parser {
diff --git a/src/main/input-output/input/json-parsing/rules_parser.cpp b/src/main/input-output/input/json-parsing/rules_parser.cpp
index 9154ffd..7b9de84 100644
--- a/src/main/input-output/input/json-parsing/rules_parser.cpp
+++ b/src/main/input-output/input/json-parsing/rules_parser.cpp
@@ -8,6 +8,7 @@
#include "rules_parser.h"
#include "json_helper.h"
#include "../sol_preset_types.h"
+#include "../../../game/card.h"
using namespace std;
using namespace rapidjson;
diff --git a/src/main/input-output/output/state_printer.cpp b/src/main/input-output/output/state_printer.cpp
index bfb6c7d..1d1c182 100644
--- a/src/main/input-output/output/state_printer.cpp
+++ b/src/main/input-output/output/state_printer.cpp
@@ -112,17 +112,5 @@ void state_printer::print_top_of_pile(ostream& stream,
}
void state_printer::print_card(std::ostream& s, const card c) {
- switch(c.get_rank()) {
- case 1 : s << "A"; break;
- case 11: s << "J"; break;
- case 12: s << "Q"; break;
- case 13: s << "K"; break;
- default: s << int(c.get_rank());
- }
- switch(c.get_suit()) {
- case card::suit_t::Spades : s << "S"; break;
- case card::suit_t::Hearts : s << "H"; break;
- case card::suit_t::Clubs : s << "C"; break;
- case card::suit_t::Diamonds: s << "D"; break;
- }
+ s << c.to_string();
}
diff --git a/src/main/main.cpp b/src/main/main.cpp
index ac81a19..78a3551 100644
--- a/src/main/main.cpp
+++ b/src/main/main.cpp
@@ -18,7 +18,7 @@ namespace po = boost::program_options;
const optional<sol_rules> gen_rules(command_line_helper&);
void solve_random_game(int, const sol_rules&);
void solve_input_files(vector<string>, const sol_rules&);
-void solve_game(const game_state&, const sol_rules&);
+void solve_game(const game_state&);
int main(int argc, const char* argv[]) {
@@ -66,7 +66,7 @@ const optional<sol_rules> gen_rules(command_line_helper& clh) {
void solve_random_game(int seed, const sol_rules& rules) {
LOG_INFO ("Attempting to solve with seed: " << seed << "...");
game_state gs(rules, seed);
- solve_game(gs, rules);
+ solve_game(gs);
}
void solve_input_files(const vector<string> input_files, const sol_rules& rules) {
@@ -79,7 +79,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, rules);
+ solve_game(gs);
} catch (const runtime_error& error) {
string errmsg = "Error parsing deal file: ";
@@ -89,8 +89,8 @@ void solve_input_files(const vector<string> input_files, const sol_rules& rules)
}
}
-void solve_game(const game_state& gs, const sol_rules& rules) {
- solver solv(gs, rules);
+void solve_game(const game_state& gs) {
+ solver solv(gs);
bool solution = solv.run();
if (solution) {
diff --git a/src/main/solver/solver.cpp b/src/main/solver/solver.cpp
index bd19351..9d25c35 100644
--- a/src/main/solver/solver.cpp
+++ b/src/main/solver/solver.cpp
@@ -13,8 +13,8 @@
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::solver(const game_state& gs)
+ : initial_state(gs), states_searched(0) {}
solver::node::node(const game_state::move m,
vector<game_state::move> uc)
@@ -27,7 +27,7 @@ bool solver::run() {
states_searched++;
LOG_DEBUG (state);
frontier.emplace_back(game_state::move(0,0), state.get_legal_moves());
- global_cache.insert(state.get_data());
+ cache.insert(state);
while (!frontier.empty()) {
node& current = frontier.back();
@@ -41,7 +41,7 @@ bool solver::run() {
// (unless it's the null first move)
if (frontier.size() > 1) {
state.undo_move(current.move);
- assert(global_cache.count(state.get_data()) == 1);
+ assert(cache.contains(state));
LOG_DEBUG (state);
}
// Returns to the previous state
@@ -54,7 +54,7 @@ bool solver::run() {
state.make_move(next_move);
// Insert the state into the global cache
- bool is_new_state = global_cache.insert(state.get_data()).second;
+ bool is_new_state = cache.insert(state);
if (is_new_state) {
states_searched++;
LOG_DEBUG (state);
@@ -64,7 +64,7 @@ bool solver::run() {
} else {
// If we've seen the state before, undoes the move
state.undo_move(next_move);
- assert(global_cache.count(state.get_data()) == 1);
+ assert(cache.contains(state));
}
}
}
diff --git a/src/main/solver/solver.h b/src/main/solver/solver.h
index 563a11e..526bd53 100644
--- a/src/main/solver/solver.h
+++ b/src/main/solver/solver.h
@@ -7,17 +7,13 @@
#include <string>
#include <vector>
-#include <unordered_set>
-#include "../game/game_state.h"
+#include "../game/global_cache.h"
#include "../game/sol_rules.h"
class solver {
public:
- std::unordered_set<
- std::vector<pile>,
- boost::hash<std::vector<pile>>
- > global_cache;
+ global_cache cache;
struct node {
explicit node(game_state::move, std::vector<game_state::move>);
@@ -25,14 +21,13 @@ public:
std::vector<game_state::move> unsearched_children;
};
- solver(const game_state&, const sol_rules&);
+ explicit solver(const game_state&);
bool run();
void print_solution() const;
private:
const game_state initial_state;
- const sol_rules rules;
std::vector<node> frontier;
int states_searched;
};
diff --git a/src/test/gloabl_cache_test.cpp b/src/test/gloabl_cache_test.cpp
new file mode 100644
index 0000000..beb1e0f
--- /dev/null
+++ b/src/test/gloabl_cache_test.cpp
@@ -0,0 +1,102 @@
+//
+// Created by thecharlesblake on 1/11/18.
+//
+
+#include <gtest/gtest.h>
+
+#include "test_helper.h"
+#include "../main/game/game_state.h"
+#include "../main/game/global_cache.h"
+
+typedef sol_rules::build_policy pol;
+
+TEST(GlobalCache, BuildSameSuit) {
+ test_helper::run_card_cache_test(pol::SAME_SUIT, false, false);
+}
+
+TEST(GlobalCache, BuildRedBlack) {
+ test_helper::run_card_cache_test(pol::RED_BLACK, false, true);
+}
+
+TEST(GlobalCache, BuildAny) {
+ test_helper::run_card_cache_test(pol::ANY_SUIT, true, true);
+}
+
+TEST(GlobalCache, BuildNone) {
+ test_helper::run_card_cache_test(pol::NO_BUILD, true, true);
+}
+
+TEST(GlobalCache, CommutativeTableauPiles) {
+ sol_rules rules;
+ rules.tableau_pile_count = 3;
+ rules.build_pol = sol_rules::build_policy::SAME_SUIT;
+ game_state gs(rules, 0);
+ global_cache cache;
+
+ cache.insert ({{card("AC")},{card("2D")},{card("3H")}});
+ ASSERT_TRUE (cache.contains({{card("2D")},{card("3H")},{card("AC")}}));
+ ASSERT_FALSE(cache.contains({{card("3H")},{card("2D")},{card("3H")}}));
+
+ // Test with empty piles
+ cache.clear();
+ cache.insert ({{card("4C")},{card("5D")},{}});
+ ASSERT_TRUE (cache.contains({{},{card("4C")},{card("5D")}}));
+ ASSERT_FALSE(cache.contains({{},{card("4C")},{}}));
+
+ // Test with piles of size > 1
+ cache.clear();
+ cache.insert ({{card("6C"),card("7D")},{card("8C")},{card("9D")}});
+ ASSERT_TRUE (cache.contains({{card("8C")},{card("6C"),card("7D")},{card("9D")}}));
+ ASSERT_FALSE(cache.contains({{card("8C")},{card("6C"),card("KD")},{card("9D")}}));
+
+ rules.tableau_pile_count = 0;
+ game_state _gs(rules, 0);
+}
+
+TEST(GlobalCache, CommutativeReserve) {
+ sol_rules rules;
+ rules.reserve_size = 3;
+ rules.build_pol = sol_rules::build_policy::SAME_SUIT;
+ game_state gs(rules, 0);
+ global_cache cache;
+
+ cache.insert ({{card("AC")},{card("2D")},{card("3H")}});
+ ASSERT_TRUE (cache.contains({{card("2D")},{card("3H")},{card("AC")}}));
+ ASSERT_FALSE(cache.contains({{card("3H")},{card("2D")},{card("3H")}}));
+
+ // Test with empty piles
+ cache.clear();
+ cache.insert ({{card("4C")},{card("5D")},{}});
+ ASSERT_TRUE (cache.contains({{},{card("4C")},{card("5D")}}));
+ ASSERT_FALSE(cache.contains({{},{card("4C")},{}}));
+
+ // Test with piles of size > 1
+ cache.clear();
+ cache.insert ({{card("6C"),card("7D")},{card("8C")},{card("9D")}});
+ ASSERT_TRUE (cache.contains({{card("8C")},{card("6C"),card("7D")},{card("9D")}}));
+ ASSERT_FALSE(cache.contains({{card("8C")},{card("6C"),card("KD")},{card("9D")}}));
+
+ rules.reserve_size = 0;
+ game_state _gs(rules, 0);
+}
+
+TEST(GlobalCache, CommutativeCells) {
+ sol_rules rules;
+ rules.cells = 3;
+ rules.build_pol = sol_rules::build_policy::SAME_SUIT;
+ game_state gs(rules, 0);
+ global_cache cache;
+
+ cache.insert ({{card("AC")},{card("2D")},{card("3H")}});
+ ASSERT_TRUE (cache.contains({{card("2D")},{card("3H")},{card("AC")}}));
+ ASSERT_FALSE(cache.contains({{card("3H")},{card("2D")},{card("3H")}}));
+
+ // Test with empty piles
+ cache.clear();
+ cache.insert ({{card("4C")},{card("5D")},{}});
+ ASSERT_TRUE (cache.contains({{},{card("4C")},{card("5D")}}));
+ ASSERT_FALSE(cache.contains({{},{card("4C")},{}}));
+
+ rules.cells = 0;
+ game_state _gs(rules, 0);
+}
diff --git a/src/test/test_helper.cpp b/src/test/test_helper.cpp
index 14218f7..5758165 100644
--- a/src/test/test_helper.cpp
+++ b/src/test/test_helper.cpp
@@ -3,6 +3,7 @@
//
#include <rapidjson/document.h>
+#include <gtest/gtest.h>
#include "test_helper.h"
#include "../main/game/game_state.h"
@@ -10,6 +11,8 @@
#include "../main/input-output/input/json-parsing/json_helper.h"
#include "../main/input-output/input/json-parsing/rules_parser.h"
+#define ASSERT_(t_f, statement) ASSERT_TRUE((statement) == t_f)
+
using namespace rapidjson;
using namespace std;
@@ -18,7 +21,70 @@ bool test_helper::is_solvable(const std::string& input_file, const std::string&
const sol_rules rules = rules_parser::from_preset(preset_type);
game_state gs(rules, in_doc);
- solver sol(gs, rules);
+ solver sol(gs);
return sol.run();
}
+
+void test_helper::run_card_cache_test(sol_rules::build_policy bp,
+ bool assert_dif_col,
+ bool assert_same_col) {
+ sol_rules rules;
+ rules.tableau_pile_count = 1;
+ rules.build_pol = bp;
+ game_state gs(rules, 0);
+
+ for (uint8_t suit_idx = 0; suit_idx < 4; suit_idx++) {
+ for (card::rank_t rank = 1; rank <= 13; rank++) {
+ global_cache cache;
+
+ // c2 is the same as c_ but with a different suit
+ const card c = card(suit_idx, rank);
+ const card c_dif_col = card(uint8_t((suit_idx + 1) % 4), rank);
+ const card c_same_col = card(uint8_t((suit_idx + 2) % 4), rank);
+ const card c_dif_rank = card(suit_idx, card::rank_t((rank % 13) + 1));
+
+ const game_state s = {{c}};
+ const game_state s_dif_suit = {{c_dif_col}};
+ const game_state s_same_col = {{c_same_col}};
+ const game_state s_dif_rank = {{c_dif_rank}};
+
+ cache.insert(s);
+
+ ASSERT_TRUE(cache.contains(s)) << "Contains self";
+
+ ASSERT_(assert_dif_col, hash_value(s) == hash_value(s_dif_suit))
+ << "Insert: " << c.to_string()
+ << ", Comp: " << c_dif_col.to_string();
+ ASSERT_(assert_dif_col, global_cache::game_state_pred()(s, s_dif_suit))
+ << "Insert: " << c.to_string()
+ << ", Comp: " << c_dif_col.to_string();
+ ASSERT_(assert_dif_col, cache.contains(s_dif_suit))
+ << "Insert: " << c.to_string()
+ << ", Comp: " << c_dif_col.to_string();
+
+ ASSERT_(assert_same_col, hash_value(s) == hash_value(s_same_col))
+ << "Insert: " << c.to_string()
+ << ", Comp: " << c_same_col.to_string();
+ ASSERT_(assert_same_col, global_cache::game_state_pred()(s, s_same_col))
+ << "Insert: " << c.to_string()
+ << ", Comp: " << c_same_col.to_string();
+ ASSERT_(assert_same_col, cache.contains(s_same_col))
+ << "Insert: " << c.to_string()
+ << ", Comp: " << c_same_col.to_string();
+
+ ASSERT_FALSE(hash_value(s) == hash_value(s_dif_rank))
+ << "Insert: " << c.to_string()
+ << ", Comp: " << c_dif_rank.to_string();
+ ASSERT_FALSE(global_cache::game_state_pred()(s, s_dif_rank))
+ << "Insert: " << c.to_string()
+ << ", Comp: " << c_dif_rank.to_string();
+ ASSERT_FALSE(cache.contains(s_dif_rank))
+ << "Insert: " << c.to_string()
+ << ", Comp: " << c_dif_rank.to_string();
+ }
+ }
+
+ rules.tableau_pile_count = 0;
+ game_state _gs(rules, 0);
+}
diff --git a/src/test/test_helper.h b/src/test/test_helper.h
index 5b8e755..fe7f8c7 100644
--- a/src/test/test_helper.h
+++ b/src/test/test_helper.h
@@ -7,9 +7,12 @@
#include <string>
+#include "../main/game/sol_rules.h"
+
class test_helper {
public:
static bool is_solvable(const std::string&, const std::string&);
+ static void run_card_cache_test(sol_rules::build_policy, bool, bool);
};