vendredi 26 avril 2013

Mastermind: a starting point...

As I start to build an algorithm to compete in an on-line Mastermind tournament, I build the following code to generate random hidden code of 4 peg from a list of 6 color (6^4 possibilities...).

The next step will be the interactive guess from a user (stdin), check to put the white and black mark, and finally the state win or lose.... (let see in future post)...


#include <string>
#include <map>
#include <algorithm>
#include <time.h>
#include <iostream>
using namespace std;

#include "boost/assign.hpp"
using namespace boost::assign;

enum color_e { white = 0, blue, green, yellow, orange, red };
typedef map<color_e, char> color_code_map_t;
typedef pair<color_e, char> color_t;
typedef vector<color_t> gess_code_t;
typedef vector<color_t> hidden_code_t;

const color_code_map_t color_code = map_list_of (color_e::white, 'A')(color_e::blue, 'B')(color_e::green, 'C')(color_e::yellow, 'D')(color_e::orange, 'E')(color_e::red, 'F') ;
const auto comb_length = 4;
const auto nb_line = 8;
hidden_code_t TheHiddenCode(comb_length);

struct acc_char {
void operator () (color_t c) {
acc_ += c.second;
}
string get() {return acc_;}
string acc_;
};

template<typename T> string colorCodeString(const T& m) {
bool is_vector_of_peg = std::is_same<T, gess_code_t>::value || std::is_same<T, hidden_code_t>::value ;
if(!is_vector_of_peg)
return ""; //or throw ?
acc_char acc;
return std::for_each(begin(m), end(m), acc).get();
}
color_t ChooseRandomPeg() { return *color_code.find((color_e)(rand() % color_code.size())); }



And a small main to check the random 'hidden code' generation:


int main() {
do
{
srand( time(0) ),
generate( TheHiddenCode.begin(), TheHiddenCode.end(), ChooseRandomPeg );
std::cout << colorCodeString(TheHiddenCode);
} while (getchar() != EOF);
return 0;
}

Aucun commentaire :

Enregistrer un commentaire