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" );
}











Ada: with Ada.Text_IO;
with Ada.Containers.Vectors;
with Ada.Numerics.Discrete_Random;

procedure Bulls_Player is

   
   package Nat_IO is new Ada.Text_IO.Integer_IO (Natural);

   
   use type Ada.Containers.Count_Type;

   
   Guessing_Length : constant := 4;

   
   type Digit is range 1 .. 9;
   
   type Sequence is array (1 .. Guessing_Length) of Digit;

   
   package Sequence_Vectors is new Ada.Containers.Vectors
     (Element_Type => Sequence,
      Index_Type   => Positive);

   
   function Is_Valid (S : Sequence) return Boolean is
      Appeared : array (Digit) of Boolean := (others => False);
   begin
      for I in S'Range loop
         if Appeared (S (I)) then
            return False;
         end if;
         Appeared (S (I))  := True;
      end loop;
      return True;
   end Is_Valid;

   
   procedure Fill_Pool (Pool : in out Sequence_Vectors.Vector) is
      Finished : exception;
      
      function Next (S : Sequence) return Sequence is
         Result : Sequence := S;
         Index  : Positive := S'Last;
      begin
         loop
         
            if Result (Index) = Digit'Last then
               Result (Index) := Digit'First;
               
               
               if Index = Result'First then
                  raise Finished;
               end if;
               Index := Index - 1;
            else
               Result (Index) := Result (Index) + 1;
               return Result;
            end if;
         end loop;
      end Next;
      X        : Sequence := (others => 1);
   begin
      loop
      
         if Is_Valid (X) then
            Pool.Append (X);
         end if;
         X := Next (X);
      end loop;
   exception
      when Finished =>
         
         
         null;
   end Fill_Pool;

   
   function Random_Index (Pool : Sequence_Vectors.Vector) return Positive is
      subtype Possible_Indexes is Positive range
        Pool.First_Index .. Pool.Last_Index;
      package Index_Random is new Ada.Numerics.Discrete_Random
        (Possible_Indexes);
      Index_Gen : Index_Random.Generator;
   begin
      Index_Random.Reset (Index_Gen);
      return Index_Random.Random (Index_Gen);
   end Random_Index;

   
   procedure Get_Answer (S : Sequence; Bulls, Cows : out Natural) is
      Valid : Boolean := False;
   begin
      Bulls := 0;
      Cows  := 0;
      while not Valid loop
         
         Ada.Text_IO.Put ("How is the score for:");
         for I in S'Range loop
            Ada.Text_IO.Put (Digit'Image (S (I)));
         end loop;
         Ada.Text_IO.New_Line;
         begin
            Ada.Text_IO.Put ("Bulls:");
            Nat_IO.Get (Bulls);
            Ada.Text_IO.Put ("Cows:");
            Nat_IO.Get (Cows);
            if Bulls + Cows <= Guessing_Length then
               Valid := True;
            else
               Ada.Text_IO.Put_Line ("Invalid answer, try again.");
            end if;
         exception
            when others =>
               null;
         end;
      end loop;
   end Get_Answer;

   
   procedure Strip
     (V           : in out Sequence_Vectors.Vector;
      S           : Sequence;
      Bulls, Cows : Natural)
   is
      function Has_To_Be_Removed (Position : Positive) return Boolean is
         Testant    : constant Sequence := V.Element (Position);
         Bull_Score : Natural           := 0;
         Cows_Score : Natural := 0;
      begin
         for I in Testant'Range loop
            for J in S'Range loop
               if Testant (I) = S (J) then
                  
                  if I = J then
                     Bull_Score := Bull_Score + 1;
                  else
                     Cow_Score := Cow_Score + 1;
                  end if;
               end if;
            end loop;
         end loop;
         return Cow_Score /= Cows or else Bull_Score /= Bulls;
      end Has_To_Be_Removed;
   begin
      for Index in reverse V.First_Index .. V.Last_Index loop
         if Has_To_Be_Removed (Index) then
            V.Delete (Index);
         end if;
      end loop;
   end Strip;

   
   procedure Solve is
      All_Sequences : Sequence_Vectors.Vector;
      Test_Index    : Positive;
      Test_Sequence : Sequence;
      Bulls, Cows   : Natural;
   begin
      
      Fill_Pool (All_Sequences);
      loop
      
         Test_Index    := Random_Index (All_Sequences);
         Test_Sequence := All_Sequences.Element (Test_Index);
         
         Get_Answer (Test_Sequence, Bulls, Cows);
         
         exit when Bulls = 4;
         All_Sequences.Delete (Test_Index);
         Strip (All_Sequences, Test_Sequence, Bulls, Cows);
         exit when All_Sequences.Length <= 1;
      end loop;
      if All_Sequences.Length = 0 then
         
         Ada.Text_IO.Put_Line
           ("I give up, there has to be a bug in" &
            "your scoring or in my algorithm.");
      else
         if All_Sequences.Length = 1 then
            Ada.Text_IO.Put ("The sequence you thought has to be:");
            Test_Sequence := All_Sequences.First_Element;
         else
            Ada.Text_IO.Put ("The sequence you thought of was:");
         end if;
         for I in Test_Sequence'Range loop
            Ada.Text_IO.Put (Digit'Image (Test_Sequence (I)));
         end loop;
      end if;
   end Solve;

begin
   
   Ada.Text_IO.Put_Line ("Bulls and Cows, Your turn!");
   Ada.Text_IO.New_Line;
   Ada.Text_IO.Put_Line
     ("Think of a sequence of" &
      Integer'Image (Guessing_Length) &
      " different digits.");
   Ada.Text_IO.Put_Line ("I will try to guess it. For each correctly placed");
   Ada.Text_IO.Put_Line ("digit I score 1 Bull. For each digit that is on");
   Ada.Text_IO.Put_Line ("the wrong place I score 1 Cow. After each guess");
   Ada.Text_IO.Put_Line ("you tell me my score.");
   Ada.Text_IO.New_Line;
   Ada.Text_IO.Put_Line ("Let's start.");
   Ada.Text_IO.New_Line;
   
   Solve;
end Bulls_Player;