From 3eff79ed14f1fda1f148a9a4c5c3a1ae4edbee37 Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Thu, 26 Oct 2017 14:51:13 +0100 Subject: BH Solver with path outputted, based on user input --- CMakeLists.txt | 2 +- src/main/black_hole_state.cpp | 74 ------------------ src/main/black_hole_state.h | 36 --------- src/main/card.cpp | 18 ++--- src/main/card.h | 1 - src/main/command_line_helper.h | 11 +-- src/main/deal_parser.cpp | 96 ++++++++++++++++++++++++ src/main/deal_parser.h | 27 +++++++ src/main/game_state.cpp | 81 ++++++++++++++++++-- src/main/game_state.h | 21 ++++-- src/main/io_utils.cpp | 101 ------------------------- src/main/io_utils.h | 27 ------- src/main/legacy_main.cpp | 121 ------------------------------ src/main/log_helper.h | 12 +-- src/main/main.cpp | 165 ++++------------------------------------- src/main/solver.cpp | 68 +++++++++++++++++ src/main/solver.h | 36 +++++++++ 17 files changed, 352 insertions(+), 545 deletions(-) delete mode 100644 src/main/black_hole_state.cpp delete mode 100644 src/main/black_hole_state.h create mode 100644 src/main/deal_parser.cpp create mode 100644 src/main/deal_parser.h delete mode 100644 src/main/io_utils.cpp delete mode 100644 src/main/io_utils.h delete mode 100644 src/main/legacy_main.cpp create mode 100644 src/main/solver.cpp create mode 100644 src/main/solver.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 36470b4..1cbfa59 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10,7 +10,7 @@ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) ## source files ############################################################### ############################################################################### -set(sources src/main/main.cpp src/main/command_line_helper.cpp src/main/command_line_helper.h src/main/log_helper.h src/main/card.h src/main/card.cpp src/main/io_utils.cpp src/main/io_utils.h src/main/game_state.cpp src/main/game_state.h src/main/black_hole_state.cpp src/main/black_hole_state.h) +set(sources src/main/main.cpp src/main/command_line_helper.cpp src/main/command_line_helper.h src/main/log_helper.h src/main/card.h src/main/card.cpp src/main/deal_parser.cpp src/main/deal_parser.h src/main/solver.cpp src/main/solver.h src/main/game_state.cpp src/main/game_state.h) set(sources_test src/test/main_test.cpp) ############################################################################### diff --git a/src/main/black_hole_state.cpp b/src/main/black_hole_state.cpp deleted file mode 100644 index 4b54bc6..0000000 --- a/src/main/black_hole_state.cpp +++ /dev/null @@ -1,74 +0,0 @@ -// -// Created by thecharlesblake on 10/23/17. -// - -#include - -#include - -#include "card.h -#include "game_state.h" -#include "black_hole_state.h" - -using namespace std; -using namespace rapidjson; - - -black_hole_state::black_hole_state(const Document& doc) - : game_state(doc), solved(false) { - // Assign hole card - assert(doc.HasMember("hole card")); - const Value& json_h_card = doc["hole card"]; - assert(json_h_card.IsArray()); - hole_card = doc["hole card"].GetString(); -}; - -vector black_hole_state::get_next_legal_states() const { - vector next; - - bool all_tableaux_empty = true; - for (int i = 0; i < tableau_piles.size(); i++) { - vector tableau_pile = tableau_piles[i]; - card top_card = tableau_pile.back(); - - if (tableau_pile.empty()) { - continue; - } else { - all_tableaux_empty = false; - } - - if (adjacent(top_card, hole_card)) { - black_hole_state s = *this; - s.move_to_hole(i); - next.push_back(s); - } - } - - // If there are no cards left in play, deal solved - solved = all_tableaux_empty; - - return next; -} - -void black_hole_state::move_to_hole(int tab_idx) { - hole_card = tableau_piles[tab_idx].back(); - tableau_piles[tab_idx].pop_back(); -} - -bool black_hole_state::is_solved() const { - return solved; -} - -ostream& black_hole_state::print(ostream& stream) const { - return game_state::print(stream) << "Hole: " << hole_card << "\n"; -} - -bool black_hole_state::adjacent(const card& a, const card& b) { - int x = a.get_rank(); - int y = b.get_rank(); - - return x == y + 1 - || x + 1 == y - || x == 1 && y == MAX_RANK - || x == MAX_RANK && y == 1; -} \ No newline at end of file diff --git a/src/main/black_hole_state.h b/src/main/black_hole_state.h deleted file mode 100644 index 75fda71..0000000 --- a/src/main/black_hole_state.h +++ /dev/null @@ -1,36 +0,0 @@ -// -// Created by thecharlesblake on 10/23/17. -// - -#ifndef SOLVITAIRE_BLACK_HOLE_STATE_H -#define SOLVITAIRE_BLACK_HOLE_STATE_H - -#include -#include - -#include - -#include "card.h -#include "game_state.h" - -class black_hole_state : public game_state { -public: - black_hole_state(const rapidjson::Document& doc); - std::vector get_next_legal_states() const override; - bool is_solved() const override; - std::ostream& print(std::ostream&) const override; - - friend std::ostream& operator<< (std::ostream&, const black_hole_state&); - -protected: - virtual static const int MAX_RANK = 13; - -private: - void move_to_hole(int); - static bool adjacent(const card& a, const card& b); - - card hole_card; - mutable bool solved; -}; - -#endif //SOLVITAIRE_BLACK_HOLE_STATE_H diff --git a/src/main/card.cpp b/src/main/card.cpp index 266d675..45de1d1 100644 --- a/src/main/card.cpp +++ b/src/main/card.cpp @@ -3,6 +3,7 @@ // #include +#include #include "card.h" @@ -34,21 +35,20 @@ char card::get_suit() const { return suit; } -std::ostream & operator<<(std::ostream & Str, card const & c) { +std::ostream & operator<<(std::ostream & s, card const & c) { std::string r; if (c.get_rank() == 1) { - r = "A"; + s << "A"; } else if (c.get_rank() <= 10) { - r = std::to_string(c.get_rank()); + s << c.get_rank(); } else if (c.get_rank() == 11) { - r = "J"; + s << "J"; } else if (c.get_rank() == 12) { - r = "Q"; + s << "Q"; } else if (c.get_rank() == 13) { - r = "K"; + s << "K"; } - r += c.get_suit(); - - return Str << r; + s << c.get_suit(); + return s; } \ No newline at end of file diff --git a/src/main/card.h b/src/main/card.h index c6fbd8e..2d9635f 100644 --- a/src/main/card.h +++ b/src/main/card.h @@ -14,7 +14,6 @@ public: int get_rank() const; char get_suit() const; - friend std::string& operator+= (std::ostream&, const game_state&); private: int rank; char suit; diff --git a/src/main/command_line_helper.h b/src/main/command_line_helper.h index 53a5a5e..3454bfb 100644 --- a/src/main/command_line_helper.h +++ b/src/main/command_line_helper.h @@ -11,16 +11,17 @@ class command_line_helper { public: command_line_helper(); bool parse(int argc, const char* argv[]); - void print_help(); - void print_no_input_error(); - void print_no_sol_type_error(); - void print_rand_plus_input_err(); const std::vector get_input_files(); const std::string get_solitaire_type(); bool get_random_deal(); bool get_help(); - bool assess_errors(); private: + bool assess_errors(); + void print_help(); + void print_no_input_error(); + void print_no_sol_type_error(); + void print_rand_plus_input_err(); + boost::program_options::options_description cmdline_options; boost::program_options::options_description main_options; boost::program_options::positional_options_description p; diff --git a/src/main/deal_parser.cpp b/src/main/deal_parser.cpp new file mode 100644 index 0000000..8a9cef1 --- /dev/null +++ b/src/main/deal_parser.cpp @@ -0,0 +1,96 @@ +// +// Created by thecharlesblake on 10/21/17. +// + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "deal_parser.h" + +using namespace std; +using namespace rapidjson; +using namespace boost; + +void deal_parser::parse(Document& doc, const std::string filename) { + const optional in_json = read_file(filename); + + if (!in_json) { + throw runtime_error("could not read file " + filename); + } + + Document sd; + gen_schema_doc(sd); + SchemaDocument schema(sd); + SchemaValidator validator(schema); + + if(!to_json(doc, *in_json)) { + throw runtime_error(filename + " not valid json"); + } + + if (!doc.Accept(validator)) { + throw runtime_error(schema_err_str(validator)); + } +} + +const optional deal_parser::read_file(const string filename) { + // Reads the file into a string + std::ifstream ifstr(filename); + std::stringstream buf; + buf << ifstr.rdbuf(); + + if (ifstr.fail()) { + return none; + } + + return buf.str(); +} + +void deal_parser::gen_schema_doc(Document& d) { + const char* schema_json = "{\"$schema\":\"http://json-schema.org/draft-04/sc" + "hema#\",\"definitions\":{\"card\":{\"type\":\"string\",\"pattern" + "\":\"^(?i)([A|[1-9]|1[0-3]|J|Q|K])([C|D|H|S])$\"}},\"type\":\"" + "object\",\"properties\":{\"tableau piles\":{\"type\":\"array\"" + ",\"items\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definit" + "ions/card\"}}},\"hole card\":{\"$ref\":\"#/definitions/card\"}}" + ",\"additionalProperties\":false,\"anyOf\":[{\"required\":[\"tableau" + " piles\"]}]}"; + + to_json(d, schema_json); +} + +bool deal_parser::to_json(rapidjson::Document& d, const char* in) { + d.Parse(in); + return !d.HasParseError(); +} + +bool deal_parser::to_json(rapidjson::Document& d, const string in) { + return to_json(d, in.c_str()); +} + +const string deal_parser::schema_err_str(const SchemaValidator& validator) { + // Input JSON is invalid according to the schema + // Output diagnostic information + string ret = "input JSON failed to match the required schema.\n"; + + StringBuffer sb; + validator.GetInvalidSchemaPointer().StringifyUriFragment(sb); + ret += "Invalid schema keyword: "; + ret += validator.GetInvalidSchemaKeyword(); + ret += "\n"; + + sb.Clear(); + validator.GetInvalidDocumentPointer().StringifyUriFragment(sb); + + ret += "Invalid document: "; + ret += sb.GetString(); + ret += "\n"; + + return ret; +} \ No newline at end of file diff --git a/src/main/deal_parser.h b/src/main/deal_parser.h new file mode 100644 index 0000000..99523f6 --- /dev/null +++ b/src/main/deal_parser.h @@ -0,0 +1,27 @@ +// +// Created by thecharlesblake on 10/21/17. +// + +#ifndef SOLVITAIRE_DEAL_PARSER_H +#define SOLVITAIRE_DEAL_PARSER_H + +#include + +#include +#include +#include + +#include "card.h" + +class deal_parser { +public: + static void parse(rapidjson::Document&, const std::string); +private: + static const boost::optional read_file(const std::string); + static void gen_schema_doc(rapidjson::Document&); + static bool to_json(rapidjson::Document&, const char*); + static bool to_json(rapidjson::Document&, const std::string); + static const std::string schema_err_str(const rapidjson::SchemaValidator&); +}; + +#endif //SOLVITAIRE_DEAL_PARSER_H diff --git a/src/main/game_state.cpp b/src/main/game_state.cpp index c6278e2..0e4f210 100644 --- a/src/main/game_state.cpp +++ b/src/main/game_state.cpp @@ -1,5 +1,5 @@ // -// Created by thecharlesblake on 10/23/17. +// Created by thecharlesblake on 10/24/17. // #include @@ -9,10 +9,13 @@ #include "game_state.h" -using namespace std; using namespace rapidjson; +using namespace std; -game_state::game_state(const Document& doc) { +// Construct an initial game state from a JSON doc +game_state::game_state(const Document& doc) : max_rank(1) { + // Construct tableau piles + assert(doc.HasMember("tableau piles")); const Value& json_tab_piles = doc["tableau piles"]; assert(json_tab_piles.IsArray()); @@ -20,29 +23,95 @@ game_state::game_state(const Document& doc) { vector tableau_pile; for (auto& json_card : json_tab.GetArray()) { - tableau_pile.push_back(card(json_card.GetString())); + card c(json_card.GetString()); + if (c.get_rank() > max_rank) max_rank = c.get_rank(); + tableau_pile.push_back(c); } tableau_piles.push_back(tableau_pile); } + + // Assign hole card + assert(doc.HasMember("hole card")); + const Value& json_h_card = doc["hole card"]; + assert(json_h_card.IsString()); + hole_card = json_h_card.GetString(); +} + +vector game_state::get_next_legal_states() const { + vector next; + + // Searches through each column for a top card that can be moved to the hole + bool all_tableaux_empty = true; + for (vector>::size_type i = 0; i < tableau_piles.size(); i++) { + vector tableau_pile = tableau_piles[i]; + + // Ignore empty piles + if (tableau_pile.empty()) { + continue; + } else { + all_tableaux_empty = false; + } + card top_card = tableau_pile.back(); + + // If a card at the top of a tableau pile is adjacent to the hole card, + // move it to the hole and add that state + if (adjacent(top_card, hole_card)) { + game_state s = *this; + s.move_to_hole(i); + next.push_back(s); + } + } + + // If there are no cards left in play, deal solved + solved = all_tableaux_empty; + + return next; +} + +bool game_state::adjacent(const card& a, const card& b) const { + int x = a.get_rank(); + int y = b.get_rank(); + + return x == y + 1 + || x + 1 == y + || (x == 1 && y == max_rank) + || (x == max_rank && y == 1); +} + +void game_state::move_to_hole(int tab_idx) { + hole_card = tableau_piles[tab_idx].back(); + tableau_piles[tab_idx].pop_back(); +} + +bool game_state::is_solved() const { + return solved; } ostream& game_state::print(ostream& stream) const { bool empty_row = false; - int row_idx = 0; + vector::size_type row_idx = 0; while (!empty_row) { empty_row = true; - for (auto tableau_pile : tableau_piles) { + + for (vector tableau_pile : tableau_piles) { if (tableau_pile.size() > row_idx) { empty_row = false; stream << tableau_pile[row_idx]; } stream << "\t"; } + + if (!empty_row) stream << "|"; + if (row_idx == 0) { + stream << " Hole card: " << hole_card; + } + stream << "\n"; row_idx++; } + return stream; } diff --git a/src/main/game_state.h b/src/main/game_state.h index 693b127..3d0d38f 100644 --- a/src/main/game_state.h +++ b/src/main/game_state.h @@ -1,5 +1,5 @@ // -// Created by thecharlesblake on 10/23/17. +// Created by thecharlesblake on 10/24/17. // #ifndef SOLVITAIRE_GAME_STATE_H @@ -10,19 +10,26 @@ #include -#include "card.h +#include "card.h" class game_state { public: game_state(const rapidjson::Document&); - virtual std::vector get_next_legal_states() const = 0; - virtual bool is_solved() const = 0; - virtual std::ostream& print(std::ostream&) const; + std::vector get_next_legal_states() const; + bool is_solved() const; + std::ostream& print(std::ostream&) const; friend std::ostream& operator<< (std::ostream&, const game_state&); -protected: - std::vector> tableau_piles; +private: + void move_to_hole(int); + bool adjacent(const card& a, const card& b) const; + + std::vector > tableau_piles; + int max_rank; + card hole_card; + mutable bool solved; }; + #endif //SOLVITAIRE_GAME_STATE_H diff --git a/src/main/io_utils.cpp b/src/main/io_utils.cpp deleted file mode 100644 index 4239c78..0000000 --- a/src/main/io_utils.cpp +++ /dev/null @@ -1,101 +0,0 @@ -// -// Created by thecharlesblake on 10/21/17. -// - -#include -#include -#include -#include - -#include -#include -#include -#include - -#include "io_utils.h" - -using namespace std; -using namespace rapidjson; -using namespace boost; - -void io_utils::parse(Document& doc, const std::string filename) { - const optional in_json = read_file(filename); - - if (!in_json) { - throw runtime_error("could not read file " + filename); - } - - Document sd; - gen_schema_doc(sd); - SchemaDocument schema(sd); - SchemaValidator validator(schema); - - if(!to_json(doc, *in_json)) { - throw runtime_error(filename + " not valid json"); - } - - if (!doc.Accept(validator)) { - throw runtime_error(schema_err_str(validator)); - } -} - -const optional io_utils::read_file(const string filename) { - // Reads the file into a string - std::ifstream ifstr(filename); - std::stringstream buf; - buf << ifstr.rdbuf(); - - if (ifstr.fail()) { - return none; - } - - return buf.str(); -} - -void io_utils::gen_schema_doc(Document& d) { - const char* schema_json = "{\"$schema\":\"http://json-schema.org/draft-04/sc" - "hema#\",\"definitions\":{\"card\":{\"type\":\"string\",\"pattern" - "\":\"^(?i)([A|[1-9]|1[0-3]|J|Q|K])([C|D|H|S])$\"}},\"type\":\"" - "object\",\"properties\":{\"tableau piles\":{\"type\":\"array\"" - ",\"items\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definit" - "ions/card\"}}},\"hole card\":{\"$ref\":\"#/definitions/card\"}}" - ",\"additionalProperties\":false,\"anyOf\":[{\"required\":[\"tableau" - " piles\"]}]}"; - - bool success = to_json(d, schema_json); - assert(success); -} - -bool io_utils::to_json(rapidjson::Document& d, const char* in) { - d.Parse(in); - return !d.HasParseError(); -} - -bool io_utils::to_json(rapidjson::Document& d, const string in) { - return to_json(d, in.c_str()); -} - -const string io_utils::schema_err_str(const SchemaValidator& validator) { - // Input JSON is invalid according to the schema - // Output diagnostic information - string ret = "input JSON failed to match the required schema.\n"; - - StringBuffer sb; - validator.GetInvalidSchemaPointer().StringifyUriFragment(sb); - ret += "Invalid schema: "; - ret += sb.GetString(); - ret += "\n"; - - ret += "Invalid schema keyword: "; - ret += validator.GetInvalidSchemaKeyword(); - ret += "\n"; - - sb.Clear(); - validator.GetInvalidDocumentPointer().StringifyUriFragment(sb); - - ret += "Invalid document: "; - ret += sb.GetString(); - ret += "\n"; - - return ret; -} \ No newline at end of file diff --git a/src/main/io_utils.h b/src/main/io_utils.h deleted file mode 100644 index 659a0c4..0000000 --- a/src/main/io_utils.h +++ /dev/null @@ -1,27 +0,0 @@ -// -// Created by thecharlesblake on 10/21/17. -// - -#ifndef SOLVITAIRE_DEAL_PARSER_H -#define SOLVITAIRE_DEAL_PARSER_H - -#include - -#include -#include -#include - -#include "card.h" - -class io_utils { -public: - static void parse(rapidjson::Document&, const std::string); -private: - static const boost::optional read_file(const std::string); - static void gen_schema_doc(rapidjson::Document&); - static bool to_json(rapidjson::Document&, const char*); - static bool to_json(rapidjson::Document&, const std::string); - static const std::string schema_err_str(const rapidjson::SchemaValidator&); -}; - -#endif //SOLVITAIRE_DEAL_PARSER_H diff --git a/src/main/legacy_main.cpp b/src/main/legacy_main.cpp deleted file mode 100644 index 76940df..0000000 --- a/src/main/legacy_main.cpp +++ /dev/null @@ -1,121 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include "legacy_card.h" -#include - -#if defined NDEBUG - #define LOG_DEBUG(msg) -#else - #define LOG_DEBUG(msg) BOOST_LOG_TRIVIAL(debug) << msg -#endif -#define LOG_INFO(msg) BOOST_LOG_TRIVIAL(info) << msg -#define LOG_WARNING(msg) BOOST_LOG_TRIVIAL(warning) << msg -#define LOG_ERROR(msg) BOOST_LOG_ERROR(error) << msg - -using namespace std; - -bool search(vector* >, legacy_card* hole); - -int main() -{ - const int topRank = 4; - - vector* > tableaux; - - vector shuffleCards; - for (int r = 1; r <= topRank; r++) { - for (int s = 0; s < 4; s++) { - string suit; - if (s == 0) { - suit = "D"; - } else if (s == 1) { - suit = "S"; - } else if (s == 2) { - suit = "H"; - } else { - suit = "C"; - } - - legacy_card* c = new legacy_card(r, suit); - shuffleCards.push_back(c); - } - } - - auto rng = std::default_random_engine(2); // 3 has solution - std::shuffle(std::begin(shuffleCards), std::end(shuffleCards), rng); - - for (int i = 0; i < topRank * 2; i++) { - vector* tab = new vector(); - for (int j = 0; j < 2; j++) { - int idx = i + (topRank * 2 * j); - if (shuffleCards[idx]->suit == "S" && shuffleCards[idx]->rank == 1) { - continue; - } else { - tab->push_back(shuffleCards[idx]); - } - } - tableaux.push_back(tab); - } - - legacy_card c(2, string("H")); - LOG_DEBUG(c); - - cout << (search(tableaux, new legacy_card(1, "S")) ? "Solution Found" : "No Solution"); - - return 0; -} - -bool search(vector* > tableaux, legacy_card* hole) { - // If the tableaux are all empty, return true - - // Seaches through each tableau. If the top card is one away from - // the hole card, puts it in the hole and recurses. - // If that fails then put the card back and repeat for the next foundation - // If it succeeds, return true - - // If we get to the end of the function, return false - -#ifndef NDEBUG - string stateRep; - for (unsigned int i = 0; i < 2; i++) { - for (auto tableau : tableaux) { - if (tableau->size() > i) { - cout << *(*tableau)[i]; - } - cout << "\t"; - } - cout << "\n"; - } - cout << "Hole: " << *hole << "\n"; -#endif - - bool allTableauxEmpty = true; - for (unsigned int i = 0; i < tableaux.size(); i++) { - auto tableau = tableaux[i]; - - if (tableau->empty()) { - continue; - } else { - allTableauxEmpty = false; - } - - legacy_card* topCard = tableau->back(); - if (topCard->rank == hole->rank + 1 || topCard->rank == hole->rank - 1) { - tableau->pop_back(); - - bool success = search(tableaux, topCard); - - if (success) { - return true; - } else { - tableau->push_back(topCard); - } - } - } - - return allTableauxEmpty; -} \ No newline at end of file diff --git a/src/main/log_helper.h b/src/main/log_helper.h index 8e634a7..9ac1351 100644 --- a/src/main/log_helper.h +++ b/src/main/log_helper.h @@ -5,13 +5,15 @@ #ifndef SOLVITAIRE_LOG_HELPER_H #define SOLVITAIRE_LOG_HELPER_H +#include + #if defined NDEBUG - #define LOG_DEBUG(msg) + #define LOG_DEBUG #else - #define LOG_DEBUG(msg) BOOST_LOG_TRIVIAL(debug) << msg + #define LOG_DEBUG clog << "[debug]\n" #endif -#define LOG_INFO(msg) BOOST_LOG_TRIVIAL(info) << msg -#define LOG_WARNING(msg) BOOST_LOG_TRIVIAL(warning) << msg -#define LOG_ERROR(msg) BOOST_LOG_ERROR(error) << msg +#define LOG_INFO(msg) clog << "[info]\n" +#define LOG_WARNING(msg) clog << "[warning]\n" +#define LOG_ERROR(msg) cerr << "[error]\n" #endif //SOLVITAIRE_LOG_HELPER_H diff --git a/src/main/main.cpp b/src/main/main.cpp index 7e9d132..a7e5871 100644 --- a/src/main/main.cpp +++ b/src/main/main.cpp @@ -1,12 +1,13 @@ #include -#include #include #include #include "command_line_helper.h" #include "card.h" -#include "io_utils.h" +#include "deal_parser.h" +#include "game_state.h" +#include "solver.h" using namespace rapidjson; @@ -14,8 +15,6 @@ using namespace std; namespace po = boost::program_options; -bool search(vector* >, card* hole); - int main(int argc, const char* argv[]) { // Parses the command-line options command_line_helper clh; @@ -23,162 +22,24 @@ int main(int argc, const char* argv[]) { return 1; } - for (auto filename : clh.get_input_files()) { + for (auto input_json : clh.get_input_files()) { try { - Document d; - io_utils::parse(d, filename); - - vector* > tableaux; - const Value& json_tabx = d["tableau piles"]; - assert(json_tabx.IsArray()); - - for (auto& json_tab : json_tabx.GetArray()) { - vector* tab = new vector(); - - for (auto& json_card : json_tab.GetArray()) { - card* c = new card(json_card.GetString()); - tab->push_back(c); - } - - tableaux.push_back(tab); - } + // Attempts to read the user's json into a document + Document doc; + deal_parser::parse(doc, input_json); - bool sol = search(tableaux, new card("AS")); + // Creates a game state object from the json, plus a solver + game_state gs(doc); + solver sol(gs); - cout << (sol ? "Solution Found" : "No Solution"); + cout << "Attempting to solve " << input_json << "...\n"; + sol.run(); + cout << sol; - for (vector* tab : tableaux) { - for (card* c : *tab) { - delete c; - } - delete tab; - } } catch (runtime_error& e) { cerr << "Error: " << e.what() << "\n"; } - - - /* - // Reads the file into a string - std::ifstream ifstr(filename); - std::stringstream buf; - buf << ifstr.rdbuf(); - string in_json = buf.str(); - - if (ifstr.fail()) { - cerr << "Error: could not read file '" << filename << "'\n"; - //return 1; - } - - Document sd; - const char* schema_json = "{\"$schema\":\"http://json-schema.org/draft-04/sc" - "hema#\",\"definitions\":{\"card\":{\"type\":\"string\",\"pattern" - "\":\"^(?i)([A|[1-9]|1[0-3]|J|Q|K])([C|D|H|S])$\"}},\"type\":\"" - "object\",\"properties\":{\"tableau piles\":{\"type\":\"array\"" - ",\"items\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definit" - "ions/card\"}}},\"hole cards\":{\"type\":\"array\",\"items\":{" - "\"$ref\":\"#/definitions/card\"}}},\"additionalProperties\":fa" - "lse,\"anyOf\":[{\"required\":[\"tableau piles\"]}]}"; - if (sd.Parse(schema_json).HasParseError()) { - // the schema is not a valid JSON. - assert(false); - } - SchemaDocument schema(sd); - - Document d; - if (d.Parse(in_json.c_str()).HasParseError()) { - // the input is not a valid JSON. - cerr << "in not valid json\n"; - } - SchemaValidator validator(schema); - if (d.Accept(validator)) { - vector* > tableaux; - const Value& json_tabx = d["tableau piles"]; - assert(json_tabx.IsArray()); - - for (auto& json_tab : json_tabx.GetArray()) { - vector* tab = new vector(); - - for (auto& json_card : json_tab.GetArray()) { - card* c = new card(json_card.GetString()); - tab->push_back(c); - } - - tableaux.push_back(tab); - } - - cout << (search(tableaux, new card("AS")) ? "Solution Found" : "No Solution"); - - for (vector* tab : tableaux) { - for (card* c : *tab) { - delete c; - } - delete tab; - } - - } else { - // Input JSON is invalid according to the schema - // Output diagnostic information - StringBuffer sb; - validator.GetInvalidSchemaPointer().StringifyUriFragment(sb); - printf("Invalid schema: %s\n", sb.GetString()); - printf("Invalid keyword: %s\n", validator.GetInvalidSchemaKeyword()); - sb.Clear(); - validator.GetInvalidDocumentPointer().StringifyUriFragment(sb); - printf("Invalid document: %s\n", sb.GetString()); - }*/ } return 0; } - -bool search(vector* > tableaux, card* hole) { - // If the tableaux are all empty, return true - - // Seaches through each tableau. If the top card is one away from - // the hole card, puts it in the hole and recurses. - // If that fails then put the card back and repeat for the next foundation - // If it succeeds, return true - - // If we get to the end of the function, return false - -#ifndef NDEBUG - string stateRep; - for (unsigned int i = 0; i < 2; i++) { - for (vector* tableau : tableaux) { - if (tableau->size() > i) { - cout << *((*tableau)[i]); - } - cout << "\t"; - } - cout << "\n"; - } - cout << "Hole: " << *hole << "\n"; -#endif - - bool allTableauxEmpty = true; - for (unsigned int i = 0; i < tableaux.size(); i++) { - auto tableau = tableaux[i]; - - if (tableau->empty()) { - continue; - } else { - allTableauxEmpty = false; - } - - card* topCard = tableau->back(); - if (topCard->get_rank() == hole->get_rank() + 1 || topCard->get_rank() == hole->get_rank() - 1) { - tableau->pop_back(); - - bool success = search(tableaux, topCard); - - if (success) { - return true; - } else { - tableau->push_back(topCard); - } - } - } - - return allTableauxEmpty; -} diff --git a/src/main/solver.cpp b/src/main/solver.cpp new file mode 100644 index 0000000..7e7155a --- /dev/null +++ b/src/main/solver.cpp @@ -0,0 +1,68 @@ +// +// Created by thecharlesblake on 10/24/17. +// + +#include +#include +#include + +#include "solver.h" +#include "log_helper.h" +#include "game_state.h" +#include +using namespace std; + +solver::solver(const game_state gs) : root(gs), solution(gs), + solution_found(false) {} + +solver::node::node(const game_state gs) : state(gs) {} + +bool solver::run() { + been_run = true; + + // Iteratively run a depth-first search. Nodes in the frontier are yet to + // be explored + vector frontier; + frontier.push_back(root); + while (!frontier.empty()) { + // Pop the element at the top of the stack + node current = frontier.back(); + frontier.pop_back(); + + LOG_DEBUG << current.state; + + // Create new nodes for each of the children + vector new_children = current.state.get_next_legal_states(); + for (auto it = new_children.rbegin(); it != new_children.rend(); it++) { + node n = current; + n.history.push_back(n.state); + n.state = *it; + + frontier.push_back(n); + } + + if (current.state.is_solved()) { + solution = current; + solution_found = true; + break; + } + } + + return solution_found; +} + +std::ostream& operator<< (std::ostream& stream, const solver& sol) { + if (sol.solution_found) { + stream << "Solution:\n"; + for (auto state : sol.solution.history) { + stream << state << "\n"; + } + stream << sol.solution.state << "\n"; + + } else if (sol.been_run) { + stream << "No Possible Solution\n"; + } else { + stream << "Solver has not been run yet\n"; + } + return stream; +} \ No newline at end of file diff --git a/src/main/solver.h b/src/main/solver.h new file mode 100644 index 0000000..0520cc7 --- /dev/null +++ b/src/main/solver.h @@ -0,0 +1,36 @@ +// +// Created by thecharlesblake on 10/24/17. +// + +#ifndef SOLVITAIRE_SOLVER_H +#define SOLVITAIRE_SOLVER_H + +#include +#include + +#include + +#include "game_state.h" + +class solver { +public: + solver(const game_state); + bool run(); + + friend std::ostream& operator<< (std::ostream&, const solver&); + +private: + struct node { + node(const game_state); + std::vector history; + game_state state; + }; + + const node root; + bool been_run; + node solution; + bool solution_found; +}; + + +#endif //SOLVITAIRE_SOLVER_H -- cgit v1.2.1