//--------------------------------------------------------------------------- #ifndef __BORLANDC__ #include #endif #include #include #include #pragma hdrstop #include #include #include #include //--------------------------------------------------------------------------- using namespace std; class Combination { public: Combination(int length, bool rep) : comb_(length, '.'), num_round(0) { if (rep) generate(comb_.begin(), comb_.end(), ChooseChar(&chars)); else random_sample(chars.begin(), chars.end(), comb_.begin(), comb_.end()); #ifdef _DEBUG cout << comb_ << endl; #endif Prompt(); } bool operator()(string& guess) // one round { size_t cok, pok; // right char(color or number) & place(position) guess.resize(comb_.size(), ' '); cok = accumulate(chars.begin(), chars.end(), CMatch(0, &comb_, &guess), CMatch::Count); pok = inner_product(comb_.begin(), comb_.end(), guess.begin(), 0, plus(), equal_to()); cout << pok_text << pok << cok_text << cok; bool solved = (pok == comb_.size()); if (solved) cout << " - solved!\n"; else Prompt(); return solved; } private: void Prompt() { cout << "\n\nguess " << ++num_round << " --> "; } string comb_; // actual combination; static const string chars, cok_text, pok_text; // possible chars; int num_round; class CMatch { public: CMatch(int i, const string* s1, const string* s2) : cok_(i), s1_(s1), s2_(s2) {} operator int() const { return cok_; } static CMatch Count(CMatch& cm, char c) { return CMatch( cm.cok_ + min(count(cm.s1_->begin(), cm.s1_->end(), c), count(cm.s2_->begin(), cm.s2_->end(), c)), cm.s1_, cm.s2_); } private: int cok_; const string *s1_, *s2_; }; class ChooseChar { public: ChooseChar(const string* cs) : cs_(cs) {}; char operator()() { #ifdef __BORLANDC__ return (*cs_)[random(cs_->size())]; #else return (*cs_)[rand() % cs_->size())]; #endif } private: const string *cs_; }; }; const string Combination::chars = "0123456789", Combination::cok_text = " ball:", Combination::pok_text = "strike:"; int main() { #ifdef __BORLANDC__ randomize(); #else srand(time(0)); #endif find_if(istream_iterator(cin), istream_iterator(), Combination(4, false)); return 0; } //---------------------------------------------------------------------------