Task: Bulls and cows_Player


C++: #include <iostream>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <time.h>


using namespace std;


const unsigned int LEN = 4;


class CowsAndBulls_Player
{
public:
    CowsAndBulls_Player() { fillPool(); }
    void play() { secret = createSecret(); guess(); }

private:
    void guess()
    {
	pair<int, int> res; int cc = 1;
	cout << endl << " SECRET: " << secret << endl << "==============" << endl;
	cout << "+-----------+---------+--------+\n|   GUESS   |  BULLS  |  COWS  |\n+-----------+---------+--------+\n";
	while( true )
	{
	    string gs = gimmeANumber();
	    if( gs.empty() ) { cout << endl << "Something went wrong with the scoring..." << endl << "Cannot find an answer!" << endl; return; }
	    if( scoreIt( gs, res ) ) { cout << endl << "I found the secret number!" << endl << "It is: " << gs << endl; return; }
	    cout << "|    " << gs << "   |  " << setw( 3 ) << res.first << "    |  " << setw( 3 ) << res.second << "   |\n+-----------+---------+--------+\n";
	    clearPool( gs, res );
        }
    }

    void clearPool( string gs, pair<int, int>& r )
    {
	vector<string>::iterator pi = pool.begin();
	while( pi != pool.end() )
	{
	    if( removeIt( gs, ( *pi ), r ) ) pi = pool.erase( pi );
	    else  pi++;
	}
    }

    string gimmeANumber()
    {
	if( pool.empty() ) return "";
	return pool[rand() % pool.size()];
    }

    void fillPool()
    {
	for( int x = 1234; x < 9877; x++ )
	{
	    ostringstream oss; oss << x;
	    if( check( oss.str() ) ) pool.push_back( oss.str() );
	}
    }

    bool check( string s )
    {
	for( string::iterator si = s.begin(); si != s.end(); si++ )
	{
	    if( ( *si ) == '0' ) return false;
	    if( count( s.begin(), s.end(), ( *si ) ) > 1 ) return false;
	}
	return true;
    }

    bool removeIt( string gs, string ts, pair<int, int>& res )
    {
	pair<int, int> tp; getScore( gs, ts, tp );
	return tp != res;
    }

    bool scoreIt( string gs, pair<int, int>& res )
    {
	getScore( gs, secret, res );
	return res.first == LEN;
    }

    void getScore( string gs, string st, pair<int, int>& pr )
    {
	pr.first = pr.second = 0;
	for( unsigned int ui = 0; ui < LEN; ui++ )
	{
	    if( gs[ui] == st[ui] ) pr.first++;
	    else
	    {
		for( unsigned int vi = 0; vi < LEN; vi++ )
		    if( gs[ui] == st[vi] ) pr.second++;
	    }
	}
    }

    string createSecret()
    {
	string n = "123456789", rs = "";
	while( rs.length() < LEN )
	{
	    int r = rand() % n.length();
	    rs += n[r]; n.erase( r, 1 );
	}
	return rs;
    }

    string secret;
    vector<string> pool;
};

int main( int argc, char* argv[] )
{
    srand( static_cast<unsigned int>( time( NULL ) ) ); CowsAndBulls_Player cb;
    cb.play(); cout << endl << endl;
    return system( "pause" );
}







Python: from itertools import permutations
from random import shuffle

try:
    raw_input
except:
    raw_input = input
try:
    from itertools import izip
except:
    izip = zip
    
digits = '123456789'
size = 4

def parse_score(score):
    score = score.strip().split(',')
    return tuple(int(s.strip()) for s in score)

def scorecalc(guess, chosen):
    bulls = cows = 0
    for g,c in izip(guess, chosen):
        if g == c:
            bulls += 1
        elif g in chosen:
            cows += 1
    return bulls, cows

choices = list(permutations(digits, size))
shuffle(choices)
answers = []
scores  = []

print ("Playing Bulls & Cows with %i unique digits\n" % size)
       
while True:
    ans = choices[0]
    answers.append(ans)
    
    score = raw_input("Guess %2i is %*s. Answer (Bulls, cows)? "
                      % (len(answers), size, ''.join(ans)))
    score = parse_score(score)
    scores.append(score)
    
    found =  score == (size, 0)
    if found:
        print ("Ye-haw!")
        break
    choices = [c for c in choices if scorecalc(c, ans) == score]
    if not choices:
        print ("Bad scoring? nothing fits those scores you gave:")
        print ('  ' +
               '\n  '.join("%s -> %s" % (''.join(an),sc)
                           for an,sc in izip(answers, scores)))
        break